I have a WCF Webservice, in which send a data model and i get this in Android by JSon(By Entity Framework),any ways,
I can successfully get that JSON by this code and store all JSON Objects in JSONArray in the AsyncTas class, and in :
public class Consume extends AsyncTask<Void, Void, Void> {
InputStream inputStream = null;
String result = "";
private ArrayList<Contact> contacts = new ArrayList<Contact>();
#Override
protected Void doInBackground(Void... params) {
String URL = "http://x.x.x.x/MyWCF/Service1.svc/rest/getContact";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(post);
HttpEntity httpEntity = httpResponse.getEntity();
//post.setHeader("content-type", "application/json");
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncoding", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
JSONObject object = new JSONObject(result);
JSONArray jArray = object.getJSONArray("getContactResult"); //here i create the JsonArray of all JsonObjects
//Here is the solutions, We make a list of out Contact and make it as down
List<Contact> contacts;
Type listType = new TypeToken<List<Contact>>() {
}.getType();
contacts= new Gson().fromJson(String.valueOf(jArray), listType);
//And here solution is ended !
} catch (JSONException e) {
e.printStackTrace();
}
}
And i created a Contact class in android, by this code :
public class Contact {
#SerializedName("name")
private String name;
#SerializedName("lastName")
private String lastName;
#SerializedName("phoneNumber")
private String phoneNumber;
#SerializedName("latitude")
private String latitude;
#SerializedName("longitude")
private String longitude;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLatitude() {
return latitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLongitude() {
return longitude;
}
}
And i parse this JSONArray by Old ways !
By this method :
ArrayList<Contact> setFields(JSONArray jsonArray) {
ArrayList<Contact> contacts = new ArrayList<Contact>();
for(int i=0; i<jsonArray.length(); i++) {
try {
Contact contact = new Contact();
JSONObject object = (JSONObject) jsonArray.get(i);
contact.setName(object.getString("name"));
contact.setLastName(object.getString("lastName"));
contact.setPhoneNumber(object.getString("phoneNumber"));
contact.setLatitude(object.getString("latitude"));
contact.setLongitude(object.getString("longitude"));
contacts.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
return contacts;
}
It works, but I do not want to handle and parse JSONArray by this old way and wanna use GSON instead,any one can help me with this sample?
Here is my JSONArray and JSON Object :
{
"getContactResult": [
{
"id": 2041,
"lastName": "xxxx",
"latitude": xxx,
"longitude": xxx,
"name": "xxxx",
"phoneNumber": "xxxx"
}
]
}
Thx
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
List<Contact> contacts;
Type listType = new TypeToken<List<Contact>>() {
}.getType();
contacts= new Gson().fromJson(jsonArray, listType);
This should work. make sure that your model class has same name as of json parameters and datatype. it will parse the jsonarray to type List of java
This already answered but i want to share one thing for you.Easy and best way
There is one plugin Gson for android studio.You need to install.Then go to CTRL + insert.
You can create gson file.
Enter some name for java file.
Click that file then Paste you json data. Click ok.
You can see your created json to gson format.
thanks hope this will help you.
Kotlin Solution
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
val gson = Gson()
val type = object : TypeToken<List<Contact>>() {}.type
val listContact : KycProperties = gson.fromJson(jArray.toString(), type) as Contact
Java Solution
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
List<Contact> listContact;
Type type = new TypeToken<List<Contact>>() {
}.getType();
listContact= new Gson().fromJson(jsonArray.toString(), type);
Combining Gson and JSON (a different approach), Simple for newbies to understand. If your gson containing json array.
ArrayList<Sukh>sukhs new ArrayList<>();
Gson gson = new Gson();
try {
JSONArray jsonArray = new JSONArray(fullJsonArrayString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject=jsonArray.getJSONObject(i);
Sukh sukhObject = gson.fromJson(jsonObject.toString(), Sukh.class);
sukhs.add(sukhObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
Related
hello i am trying to use a POST method of volley to get a string something like this
{"Date":"01-04-2017","PartyName":"Customer3","Supplier":"Supplier2",
"Items":[{"ItemNo":0,"ItemName":"a","Quantity":100,"DueDate":"01-04-
2017","Price":80,"Amount":80000}]}
here is my code:
JSONObject singleorder= new JSONObject();
try {
singleorder.put("Date",Get_date);
singleorder.put("PartyName",Get_partyname);
singleorder.put("Supplier", Get_supplier);
JSONArray arr = singleorder.getJSONArray("Items");
for(int i=0;i<arr.length();i++){
JSONObject obj = arr.getJSONObject(i);
//obj.put("ItemNo",Get_itemno);
obj.put("ItemName",Get_itemname);
obj.put("Quantity",Get_quantity);
obj.put("Price",Get_price);
obj.put("Amount",Get_amount);
}
//JSONArray item = new JSONArray("Items");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
when i run my code it, doesnt take the Array "item". it gives me the error:
org.sjon.JSONException:No value for Items.
where i am doing wrong?
JSONObject singleorder= new JSONObject();
try {
singleorder.put("Date",Get_date);
singleorder.put("PartyName",Get_partyname);
singleorder.put("Supplier", Get_supplier);
int loopSize = Get_No_items(); //Or just initialize it as 1 in your particular case
JSONArray arr = new JSONArray();
for(int i=0;i<loopSize;i++){
JSONObject obj = new JSONObject();
//obj.put("ItemNo",Get_itemno);
obj.put("ItemName",Get_itemname);
obj.put("Quantity",Get_quantity);
obj.put("Price",Get_price);
obj.put("Amount",Get_amount);
arr.put(obj);
}
singleorder.put("Items", arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Do something like this, it will be more error-free
class A implements Serializable{
private String name;
private B addresses[];
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public B[] getAddresses() {
return addresses;
}
public void setAddresses(B[] addresses) {
this.addresses = addresses;
}}
class B implements Serializable{
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
And finally
{A a = new A();
a.setName("abc");
B addresses[] = new B[1];
addresses[0] = new B();
addresses[0].setAddress("xyz");
a.setAddresses(addresses);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(a);}
and it will produce JSON string like
{"name":"zafa","addresses":[{"address":"xyz"}]}
You can create json array like this
private JSONArray getJsonArray(ArrayList<Object> array) {
JSONArray jsonArray = new JSONArray();
if (array != null && array.size() > 0) {
for (int i = 0; i < array.size(); i++) {
JSONObject jsonObject = new JSONObject();
Object object = array.get(i);
try {
jsonObject.put(DESCRIPTION, object.getData());
jsonObject.put(IMAGE_URL, object.getAnotherData());
jsonArray.put(i, jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return jsonArray;
}
You have not added Items to singleorder.
You do it with a line like this:
singleorder.add(key, value);
I am completely don't know Json. Now i am working in Android project. I know how to use Array. I have Json file inside of my Asset folder in my Android Project.
and i have to fetch only standard value from json data and store it in an empty array. my json data is,
[
{
"name":"aaa",
"surname":"bbb",
"age":"18",
"div":"A",
"standard":"7"
},
{
"name":"ccc",
"surname":"ddd",
"age":"17",
"div":"B",
"standard":"7"
},
{
"name":"eee",
"surname":"fff",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"ggg",
"surname":"hhh",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"sss",
"surname":"ddd",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"www",
"surname":"ggg",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"ggg",
"surname":"ccc",
"age":"18",
"div":"B",
"standard":"6"
}
]
i am not able to get the way through which i can do this. because i have to check each standard in json data and add it to the array created for storing standard valuee so that i can compare that standard values with each satndard values if its already present in array the it can check the next index in josn data and accordingly unique values can get stored on may array.
i dont know to achieve this as i am new to android as well as for json.
Use gson for easy parsing of json
TypeToken> token = new TypeToken>() {};
List animals = gson.fromJson(data, token.getType());
you can use http://www.jsonschema2pojo.org/ to create user class
public class User {
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("age")
#Expose
private String age;
#SerializedName("div")
#Expose
private String div;
#SerializedName("standard")
#Expose
private String standard;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getDiv() {
return div;
}
public void setDiv(String div) {
this.div = div;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
}
You can do this way:
//Global Declared
ArrayList<String> allStanderds = new ArrayList<>();
allStanderds.clear();
try{
JSONArray araay = new JSONArray(Your_Json_Array_String);
for (int i = 0; i <array.length() ; i++) {
JSONObject jsonObject = new array.getJSONObject(i);
String standard = jsonObject.getString("standard");
if(!allStanderds.contains(standard)){
allStanderds.add(standard);
}
}
}catch (Exception e) {
e.printStackTrace();
}
// use allStanderds ArrayList for SetAdapter for Spinner.
Happy Coding > :)
Use GSON for parsing JSON array.GSON will provide very helpful API
See my previously asked question on SO related to JSON parsing. You will get rough idea
How to parse nested array through GSON
installl GsonFormat plugin in android studio
use your json string to generate an user entity(example:UserEntity.class)
now,you can use UserEntity user=new Gson().fromJson(yourString,UserEntity.class);
now,your json string is storaged in Object user now;
Please try to use this one
try{
String assestValue = getStringFromAssets();
JSONArray arr = new JSONArray(assestValue);
int count = arr.length();
for (int i=0; i < count; i++){
JSONObject obj = arr.getJSONObject(i);
String name = obj.getString("name");
String surname = obj.getString("surname");
String age = obj.getString("age");
String div = obj.getString("div");
String standard = obj.getString("standard");
}
}catch (JSONException e){
e.printStackTrace();
}
public String getStringFromAssets(){
String str = "";
try {
StringBuilder buf = new StringBuilder();
InputStream json = getAssets().open("contents.json");//put your json name
BufferedReader in =
new BufferedReader(new InputStreamReader(json, "UTF-8"));
while ((str = in.readLine()) != null) {
buf.append(str);
}
in.close();
return str;
}catch (Exception e){
e.printStackTrace();
}
return str;
}
Enjoy programming :)
I'm trying to get JSON value by EditText.
At first I had a bunch of nullpointer exceptions, solved that. But now my function just isn't working. Been wrapping my brain over this...
I tried to create a EditText, get that value to a String, and get it over to the JSON Object. Don't know what I'm doing wrong... Or am I forgetting something?
public class MyActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
EditText edt;
Button Btngetdata;
//URL to get JSON Array
private static String url = "*";
//JSON Node Names
private static final String TAG_TAG = "tag";
private static final String TAG_ID = "id";
private static final String TAG_LAST_NAME = "last_name";
private static final String TAG_EMAIL = "country";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Btngetdata = (Button)findViewById(R.id.getdata);
edt = (EditText)findViewById(R.id.edittext);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
email1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(MyActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_TAG);
JSONObject c = user.getJSONObject(0);
String xyz = edt.getText().toString();
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
edt.setText(xyz);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
{"tag":[{"id":"1","first_name":"Philip","last_name":"Porter","email":"pporter0#admin.ch","country":"China","ip_address":"26.83.255.206"},{"id":"2","first_name":"Nancy","last_name":"Martin","email":"nmartin1#google.ca","country":"Colombia","ip_address":"160.93.80.1"},{"id":"3","first_name":"Ann","last_name":"Peterson","email":"apeterson2#utexas.edu","country":"China","ip_address":"251.254.74.162"},{"id":"4","first_name":"Rachel","last_name":"Clark","email":"rclark3#mayoclinic.com","country":"Brazil","ip_address":"58.218.248.5"},{"id":"5","first_name":"Heather","last_name":"Burton","email":"hburton4#creativecommons.org","country":"Ethiopia","ip_address":"244.69.119.16"},{"id":"6","first_name":"Ruth","last_name":"Lane","email":"rlane5#va.gov","country":"Brazil","ip_address":"18.173.102.54"},{"id":"7","first_name":"Andrew","last_name":"Turner","email":"aturner6#devhub.com","country":"United States","ip_address":"13.119.240.234"},{"id":"8","first_name":"Wanda","last_name":"Medina","email":"wmedina7#pagesperso-orange.fr","country":"Netherlands","ip_address":"151.139.21.237"},{"id":"9","first_name":"Robert","last_name":"Elliott","email":"relliott8#joomla.org","country":"United States","ip_address":"34.200.249.109"},{"id":"10","first_name":"Kevin","last_name":"Harrison","email":"kharrison9#nih.gov","country":"Brazil","ip_address":"106.84.164.86"}]}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
EDIT
JSONObject c = user.getJSONObject(Integer.parseInt(xyz));
I Modified to this, im getting a response other than default 1 when base value was getJSONObject(0), but now im entering 1 and im getting 2, entering 4 getting 5..
Does anyone know how to solve this one?
If you are trying to parse the whole json array then use this.In you post execute
List<String> allid = new ArrayList<String>();
JSONArray obj= jsonResponse.getJSONArray("tag");
for (int i=0; i<obj.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String id= actor.getString("id");
allNames.add(id);
}
Then you can use a for loop to get the id in the list accordingly.
Otherwise you can do this parsing Using the Gson Library(you can download Gson library here
Just create a class in your package
public class DetailArray {
public boolean status;
public List<Detail_User> details;
public class Detail_User {
public String id;
public String first_name;
public String last_name;
public String email;
public String country;
}
}
In your post execute
Where response is the json response
DetailArray detail1 = (new Gson()).fromJson(response.toString(),
DetailArray.class);
Now Suppose , if you want to set the names in a list view then
//return a arraylist
private ArrayList<String> getName(DetailArray detail) {
ArrayList name = new ArrayList<String>();
for (int i=0;i< detail.details.size();i++) {
name.add(splitStr[i]);
}
return names;
}
Setting the array adapter and setting it to a list
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
getName(detail);
listview.setAdapter(arrayAdapter);
For a particular position try like this
int positionToShow = Integer.parseInt(edt.getText().toString()) - 1;
user = json.getJSONArray(TAG_TAG);
for(int i = 0; i < user.length(); i++) {
if(positionToShow == i) {
JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
uid.setText(id);
name1.setText(name);
email1.setText(email);
}
}
i've parse your json ...acc to number entered ..and it shows exact result....refer this....
final EditText no=(EditText)findViewById(R.id.editText1);
final Button click=(Button)findViewById(R.id.button1);
click.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try
{
Toast.makeText(MainActivity.this, no.getText().toString(), 0).show();
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet("http://192.168.0.30/test.js");
HttpResponse response=client.execute(request);
HttpEntity entity=response.getEntity();
String json=EntityUtils.toString(entity);
JSONObject j1=new JSONObject(json);
JSONArray ja1=j1.getJSONArray("tag");
JSONObject j2=ja1.getJSONObject(Integer.parseInt(no.getText().toString())-1);
Toast.makeText(MainActivity.this, j2.getString("first_name").toString() , 0).show();
entity.consumeContent();
}
catch(Exception e)
{
e.getStackTrace();
Toast.makeText(MainActivity.this, e.toString() , 0).show();
}
}
});
I know that there are a few question about this subject, but I read them and I tried the soluttion but it didn't work :(
the PHP script give this json array result: data[x] =
["alon","62","1.82","22","0","70","0","1"]
(this is the data[x] variable)
I have to convert this result to Java variabls like name,weight,height etc.. but I don't know how..
please help me
my function:
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
protected void onPreExecute() {
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
data[x] = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
cancel(true);
}
return null;
}
public void onPostExecute(Void unused) {
String name = null,weight = null;
if (Error != null) {
} else {
// here I have to do something with the arrays...
Toast.makeText(getApplicationContext(),"d:" + data[x] + "o:" + name + " : " + weight, Toast.LENGTH_LONG).show();
}
x++;
}
}
Create a Modal Class for that.
class myModal {
private String name, weight, height, ...;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
//and more getters and setters
}
JSONObject json = new JSONObject(data[x]); // in your sample its a JSONArray but its wrong formatted. make sure you encode it properply with php json_encode(array("data", yourdata))...);
myModal modal = new myModal();
modal.setName(json.getString("name"));
php should be something like
<?php
$data = array("name" => "myname", "weight" => 20);
print json_encode( $data );
?>
while the json can be parsed in this case with
JSONArray json = new JSONArray(data);
for (int i = 0; i <= json.length();i++){
JSONObject jsonObj = json.getJsonObject(i);
myModal modal = new myModal();
modal.setString(jsonObj.getString("name"));
//and so on
}
make sure to read the basics for understanding
I am trying to implement an google map app that will store the google marker on the cloud database. But I have a problem to get back the coordinate of the marker on the cloud.
How do I return a List generated in an AsyncTask back to a custom java class? The problem that I have encountered right now is when I initialize a Alistener class in different class, for example, in class B:
AListener a = new Alistener( ..., ... );
...
a.getMarkerData();
List<Pair> myList = a.getList();
myList is just null, and I think because the a.getList() has executed before the data is fetched back from that cloud database in onPostExecute(). Any insight will help a lot.
This is my java class:
public class AListener {
protected static final String TAG = null;
double lat, lon;
List<Pair> myList = new ArrayList<Pair>();
CustomMarkerListener( double lat, double lon ) {
this.lat = lat;
this.lon = lon;
}
public void getMarkerData() {
MarkerDataInfo ms = new MarkerDataInfo();
ms.execute( UserLogin.ITEM_URI );
}
public void setList(List<Pair> myList ) {
this.myList = myList;
}
public List<Pair> getList() {
return this.myList;
}
}
And this is my AsyncTask an inner class of AListener:
private class MarkerDataInfo extends AsyncTask<String, Void, List<Pair>> {
List<Pair> list;
private CustomMarkerListener mLis;
public MarkerDataInfo() {}
public MarkerDataInfo( CustomMarkerListener mLis ) {
this.mLis = mLis;
}
#Override
protected List<Pair> doInBackground(String... url) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet( UserLogin.ITEM_URI);
list = new ArrayList<Pair>();
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Log.d(TAG, data);
JSONObject myjson;
try {
myjson = new JSONObject(data);
JSONArray array = myjson.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String markerOfUser = obj.get("marker").toString();
if( markerOfUser.equals( UserLogin.accountName )) {
String latname = obj.get("lat").toString();
String lonname = obj.get("lon").toString();
double latData = Double.parseDouble(latname);
double lonData = Double.parseDouble(lonname);
list.add( new Pair( latData, lonData ));
}
}
} catch (JSONException e) {
Log.d(TAG, "Error in parsing JSON");
}
} catch (ClientProtocolException e) {
Log.d(TAG, "ClientProtocolException while trying to connect to GAE");
} catch (IOException e) {
Log.d(TAG, "IOException while trying to connect to GAE");
}
return list;
}
protected void onPostExecute(List<Pair> list) {
super.onPostExecute(list);
mLis.setList( list );
Log.d("CUstome", "" + list.size());
}
}
If only one request is active at any time, you can use singleton pattern for your class.