Sunday 7 December 2014

Json Parsing in android


Here I am trying to implement jsonParsing in a Simple way using AsynTask


package com.technomobs.backdoing;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.technomobs.Interfacez.NewsLoadingCompleteInterface;
import com.technomobs.Interfacez.PhotoLoadingCompleteInterface;
import com.technomobs.Interfacez.VideoLoadingComplateInterface;
import com.technomobs.Models.HomePageModel;
import com.technomobs.Utils.Constantz;
import com.technomobs.menaproperties.R;

public class TestimonilLoading extends AsyncTask<String, Void, Object> {
ProgressDialog dialog;
ArrayList<HomePageModel> ArrhomePageModel;
ArrayList<HomePageModel> ArrhomePageModelsnd;
ArrayList<HomePageModel> ArrhomePageModelFinal;

private String errorMessage=null;
private Context context;
JSONArray jsonArraydata; String result;
JSONArray jsonArrayres;
VideoLoadingComplateInterface callback;
HomePageModel homePageModel;
JSONObject jsobj;
JSONObject jsonObject ;
boolean needloading;
public TestimonilLoading(Context context, VideoLoadingComplateInterface promo) {
this.callback=promo;
this.context=context;

Log.e("inside","gallery");
// TODO Auto-generated constructor stub
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.dialog=ProgressDialog.show(context, "", "");
this.dialog.setContentView(R.layout.custom_progressbarlayout);
// this.dialog.setMessage("Please wait..");
    this.dialog.show();
 
    this.dialog.setCancelable(false);


}
@Override
protected Object doInBackground(String... params) {

ArrhomePageModelFinal=new ArrayList<HomePageModel>();


    //First time start 0 else:10


 
    Log.e("inside", "First");
//    
try{

HttpClient clientTech = new DefaultHttpClient();
HttpPost request = new HttpPost(Constantz.getRows);




   String json = "";
  // Log.e("inside", "json"+params[0]+params[1]+params[2]+params[3]);
   // 3. build jsonObject
   if(params[0].equalsIgnoreCase("First")){
    Log.e("1nd", "1nd");
    jsonObject = new JSONObject();
   jsonObject.accumulate("param", params[1]);
   jsonObject.accumulate("start", 0);
   jsonObject.accumulate("noofrows", 10);



   }//first
   
   else{
    Log.e("2nd", "2nd");
    //2nd time start: from saved data, else:10
    jsonObject = new JSONObject();
    jsonObject.accumulate("param", params[1]);
   jsonObject.accumulate("start",  params[2]);
   jsonObject.accumulate("noofrows", 10);
 
   }
   // 4. convert JSONObject to JSON to String
   json = jsonObject.toString();
 
   Log.e("inside", "json"+json);
 
// 5. set json to StringEntity
   StringEntity se = new StringEntity(json);
   Log.e("inside", "se"+se);
// 6. set httpPost Entity
   request.setEntity(se);
   // 7. Set some headers to inform server about the type of the content
   request.setHeader("Accept", "application/json");
   request.setHeader("Content-type", "application/json");
 
// request.setEntity(new StringEntity(toPass) );
HttpResponse responseTech = clientTech.execute(request);

Log.e("test","Login:"+responseTech);
String jsonResponse = EntityUtils.toString(responseTech.getEntity());

Log.e("jsonResponse","jsonResponse:"+jsonResponse);
JSONObject reader = new JSONObject(jsonResponse);
Log.e("reader","reader:"+reader);
JSONObject sys  = reader.getJSONObject("response");
Log.e("response","response:"+sys);
jsonArraydata=sys.getJSONArray("data");

ArrhomePageModel=new ArrayList<HomePageModel>();
   if(params[0].equalsIgnoreCase("First")){
   
    Log.e("First", "First");
    needloading=true;
for(int i=0;i<jsonArraydata.length();i++)
{
jsobj=jsonArraydata.getJSONObject(i);
homePageModel=new HomePageModel();
homePageModel.id=jsobj.optString("id");
homePageModel.date_added=jsobj.optString("date_added");
homePageModel.agent=jsobj.optString("agent");
homePageModel.testi=jsobj.optString("testi");
homePageModel.name=jsobj.optString("name");
homePageModel.company=jsobj.optString("company");



ArrhomePageModel.add(homePageModel);


}//for
//
//jsonArrayres reading
   }
   //2nd time
   else{
Log.e("2nd","2nd:");

    ArrhomePageModelsnd=new ArrayList<HomePageModel>();

for(int i=0;i<jsonArraydata.length();i++)
{
jsobj=jsonArraydata.getJSONObject(i);
homePageModel=new HomePageModel();
homePageModel.id=jsobj.optString("id");
homePageModel.date_added=jsobj.optString("date_added");
homePageModel.agent=jsobj.optString("agent");
homePageModel.testi=jsobj.optString("testi");
homePageModel.name=jsobj.optString("name");
homePageModel.company=jsobj.optString("company");



ArrhomePageModelsnd.add(homePageModel);

}//for
//
if(jsonArraydata.length()==0)
{
needloading=false;
Log.e("3needloading", "needloading"+needloading);
}
else{
needloading=true;
}
FileInputStream fis;
try {
fis = context.openFileInput(Constantz.MENA_DATA_OFF+params[1]);
ObjectInputStream is = new ObjectInputStream(fis);

ArrhomePageModel = (ArrayList<HomePageModel>) is.readObject();
Log.e("2nd","2nd:"+ArrhomePageModel.size());

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrhomePageModel.addAll(ArrhomePageModelsnd);
Log.e("2nd","2nd: 2nd"+ArrhomePageModel.size());

   }//else

 

   }//try
 catch (UnsupportedEncodingException exception) {
errorMessage = exception.getMessage();
} catch (ClientProtocolException e) {
errorMessage = e.getMessage();
// e.printStackTrace();
} catch (ConnectTimeoutException e) {
errorMessage = "Time Out!";
//e.printStackTrace();
} catch (UnknownHostException e) {
errorMessage = "No Connection Available!";
//e.printStackTrace();
} catch (Exception e) {
errorMessage = "No Connection Available!";
//e.printStackTrace();
}

if (errorMessage == null) {
Log.e("errorMessage", "errorMessage 7"+errorMessage);
try {
FileOutputStream fos;
fos = context.openFileOutput(Constantz.MENA_DATA_OFF+params[1], Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(ArrhomePageModel);
os.close();
} catch (FileNotFoundException e) {
errorMessage = e.getMessage();
} catch (IOException e) {
errorMessage = e.getMessage();
}
}
else
{
Log.e("param", "param 8");
FileInputStream fis;
try {
fis = context.openFileInput(Constantz.MENA_DATA_OFF+params[1]);
ObjectInputStream is = new ObjectInputStream(fis);

ArrhomePageModel = (ArrayList<HomePageModel>) is.readObject();
Log.e("ArrhomePageModel","ArrhomePageModel final:"+ArrhomePageModel.size());

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return ArrhomePageModel;

}
@Override
protected void onPostExecute(Object result) {
if (dialog.isShowing()) {
          dialog.dismiss();
      }

callback.onVideoLoadingComplete(errorMessage, result,needloading);

}
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

package com.technomobs.backdoing;

import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.technomobs.Interfacez.RegistrationCompleteInterface;
import com.technomobs.Interfacez.TestimonilCompleteInterface;
import com.technomobs.Utils.Constantz;

public class TestimonilFormSendingLoading extends AsyncTask<String, Void, String> {
ProgressDialog dialog;

//ArrayList<QuestModel> questions;
HashMap<String, String> promoHash;
private String errorMessage=null;
private Context context;
static JSONArray jsonArray; String result;
TestimonilCompleteInterface callback;
String MobileUserID;
public TestimonilFormSendingLoading(Context context, TestimonilCompleteInterface promo) {
this.callback=promo;
this.context=context;

Log.e("inside","gallery");
// TODO Auto-generated constructor stub
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog= new ProgressDialog(context);
this.dialog.setMessage("Please wait..");
    this.dialog.show();
    this.dialog.setCancelable(false);
    Log.e("inside", "gallery");


}
@Override
protected String doInBackground(String... params) {

http://www.mena-properties.com/mena_app/mobilemanager/uploadData/


try{

HttpClient httpclient  = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constantz.UpLoadData);

    String json = "";
   // Log.e("inside", "json"+params[0]+params[1]+params[2]+params[3]);
    // 3. build jsonObject
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("p", "addtestimonial");
    jsonObject.accumulate("TestimonialUserName", ""+params[0]);
    jsonObject.accumulate("TestimonialPlace", ""+params[1]);
    jsonObject.accumulate("TestimonialComments", ""+params[2]);
    // 4. convert JSONObject to JSON to String
    json = jsonObject.toString();
    StringEntity se = new StringEntity(json);
    httppost.setEntity(se);
    httppost.setHeader("Accept", "application/json");
    httppost.setHeader("Content-type", "application/json");
HttpResponse responseTech = httpclient.execute(httppost);
//    
String jsonResponse = EntityUtils.toString(responseTech.getEntity());

Log.e("test","Login:"+jsonResponse);
JSONObject jobj=new JSONObject(jsonResponse);

JSONObject jsonArray=jobj.getJSONObject("response");

result=jsonArray.optString("status");

       if(result.equalsIgnoreCase("success"))
       {
      result="Testimonials added successfully";
           errorMessage="" ;

       }
       else{
      result="No connection available";
      errorMessage="No connection available" ;
       }

}
catch(Exception e)
{
            errorMessage="No connection available" ;
        result="No connection available";

}







return result;

}
@Override
protected void onPostExecute(String result) {
if (dialog.isShowing()) {
          dialog.dismiss();
      }


callback.onTestimonilCompleteInterface(errorMessage, result);

}
}


No comments:

Post a Comment