Calling a method on android button click - android

I am trying to make a web service call via android button click. I've managed to rectify the errors, but it shows some bugs on getting response. I receive null response. Below is my code. Could someone debug me please..!
My code:
refresh_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
HttpHandler httpHandler1 = new HttpHandler();
String res = null;
String authToken = "MlSyULrWlFgVk28";
try {
Log.d("edwLog", TAG + " get_payment_notifications " + HttpHandler.API_URL + "get_payment_notifications/" + authToken + "/");
res = httpHandler1.makeServiceCall(HttpHandler.API_URL + "get_payment_notifications/" + authToken + "/", HttpHandler.GET);
Log.d("edwLog", TAG + " response > " + res);
if (res != null) {
JSONObject jsonObject = new JSONObject(res);
String responseType = jsonObject.getString("type");
if (responseType.equals("success")) {
if (jsonObject.has("response")) {
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
notifications.add(jsonArray.getJSONObject(i));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
Log.d("edwLog", TAG + " IOException > " + e.toString());
}
}
});

Are you getting compile time error or runtime. It seems that you are trying to return a bundle from a method that has a return type void i.e.
public void onClick(View v)

Found the bug..! The mistake was, I had passed the AuthToken as a default String. Now I declared it as "null" in final, i.e., before onCreate and deleted it from inside the ClickEvent. And its done.. The right code below..
refresh_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
HttpHandler httpHandler1 = new HttpHandler();
String res = null;
try {
Log.d("edwLog", TAG + " get_payment_notifications " + HttpHandler.API_URL + "get_payment_notifications/" + AuthToken + "/");
res = httpHandler1.makeServiceCall(HttpHandler.API_URL + "get_payment_notifications/" + AuthToken + "/", HttpHandler.GET);
Log.d("edwLog", TAG + " response > " + res);
if (res != null) {
JSONObject jsonObject = new JSONObject(res);
String responseType = jsonObject.getString("type");
if (responseType.equals("success")) {
if (jsonObject.has("response")) {
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
notifications.add(jsonArray.getJSONObject(i));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
Log.d("edwLog", TAG + " IOException > " + e.toString());
}
}
});

Related

how to merge 2 data records to one in a recyclerView ? (mysql & volley)

I want to merge two data records to become one based on the same DAY, but different "Sesi" such as Sesi 1, and Sesi 2 being 1 in a recyclerVCiew
please see my application Image
here I use mySql with volley JSON + Inner Join MYSQL
Main Activity:
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ALL_JADWAL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject jadwal = array.getJSONObject(i);
String kelas = jadwal.getString("Kelas");
if (kelas.equals(Kelas)) {
jadwalHarianList.add(new JadwalHarian(
jadwal.getString("Nama_Pengajar"),
jadwal.getString("Mata_Kuliah"),
jadwal.getString("Ruang"),
jadwal.getInt("Sesi"),
jadwal.getString("Hari"),
jadwal.getString("Jam")
));
}
JadwalRV jadwalRV = new JadwalRV(getApplicationContext(), jadwalHarianList);
recyclerView.setAdapter(jadwalRV);
jadwalRV.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
JadwalRV Adapter:
public void onBindViewHolder(JadwalRV.MyViewHolder myViewHolder, int i) {
JadwalHarian jadwalHarian = mJadwalHarian.get(i);
myViewHolder.tHari.setText(jadwalHarian.getHari());
myViewHolder.tIsi.setText("Waktu\n" +
"Ruang\n" +
"Mata Kuliah\n" +
"Dosen Pengajar");
myViewHolder.thjam.setText(
"= " + jadwalHarian.getJam()+
"\n= " + jadwalHarian.getRuang() +
"\n= " + jadwalHarian.getMata_Kuliah() +
"\n= " + jadwalHarian.getNama_Pengajar() );
// SESI 2
myViewHolder.tIsi2.setText("Waktu\n" +
"Ruang\n" +
"Mata Kuliah\n" +
"Dosen Pengajar");
myViewHolder.thjam2.setText(
"= " + jadwalHarian.getJam()+
"\n= " + jadwalHarian.getRuang() +
"\n= " + jadwalHarian.getMata_Kuliah() +
"\n= " + jadwalHarian.getNama_Pengajar() );
}
Here is Structure Table which I used inner join in my PHP json
You can try like this following not obvious, but It can help you:
try
{
JSONArray array = new JSONArray();
ArrayList<HashMap<String,Object>> jadwalHarianList = new ArrayList<>();
JSONObject jsonObject=new JSONObject();
try
{
jsonObject.put("Kelas", "R28");
jsonObject.put("Sesi", "1");
jsonObject.put("Mata_Kuliah", "Pemprograman #1");
array.put(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("Kelas", "R28");
jsonObject.put("Sesi", "2");
jsonObject.put("Mata_Kuliah", "Algoritma #2");
array.put(jsonObject);
}
catch (Exception e)
{
Log.e("ldfjdlfj","data----111_jsonOb_ex>>>"+e);
}
Log.e("ldfjdlfj","data----2222>>>"+array);
String previous = "";
for (int i = 0; i < array.length(); i++) {
JSONObject jadwal = array.getJSONObject(i);
String kelas = jadwal.getString("Kelas");
String Sesi = jadwal.getString("Sesi");
String Mata_Kuliah = jadwal.getString("Mata_Kuliah");
if(kelas.equalsIgnoreCase(previous))
{
HashMap<String,Object> map = new HashMap<>();
map.put("kelas",array.getJSONObject(i-1).getString("Kelas"));
map.put("Sesi",array.getJSONObject(i-1).getString("Sesi"));
map.put("Sesi2",Sesi);
map.put("Mata_Kuliah",Mata_Kuliah);
jadwalHarianList.add(map);
}
else
{
previous = kelas;
HashMap<String,Object> map = new HashMap<>();
map.put("kelas",array.getJSONObject(i).getString("Kelas"));
map.put("Sesi",array.getJSONObject(i).getString("Sesi"));
map.put("Sesi2","");
map.put("Mata_Kuliah",Mata_Kuliah);
jadwalHarianList.add(map);
}
}
Log.e("ldfjdlfj","data----333_>>>"+jadwalHarianList);
} catch (JSONException e) {
e.printStackTrace();
}

Match `json` response with string

On click of selected date, I want to display related tasks or events.
public static List<ScheduledTasks> getResponse() {
String res = "[{\n" +
"\t\"scheduleId\": \"999\",\n" +
"\t\"eventType\": \"first\",\n" +
"\t\"impacts\": \"high\",\n" +
"\t\"startDate\": 27032018,\n" +
"\t\"endDate\": 27032018,\n" +
"\t\"machineOwner\": \"Nilesh\",\n" +
"\t\"description\": \"good\",\n" +
"\t\"status\": \"working\"\n" +
"}, ...
"}]";
return new Gson().fromJson(res, new TypeToken<List<ScheduledTasks>>(){}.getType());
this is the JSON.
Using the below
LayoutManager = new LinearLayoutManager(this);
String s = getIntent().getStringExtra("dateselected");
ScheduledTasks=getResponse();
adapter = new RecyclerAdapter(ScheduledTasks);
recyclerView.setAdapter(adapter);
List<ScheduledTasks>
I want to display only tasks for selected date.
String S date needs to be matched with json response and show particular tasks.
for date 27 only the tasks on that day should be displated.
try changing your getResponse method a bit like this so you can filter by date
public static List<ScheduledTasks> getResponse(String dateselected) {
String res = "[{\n" +
"\t\"scheduleId\": \"999\",\n" +
"\t\"eventType\": \"first\",\n" +
"\t\"impacts\": \"high\",\n" +
"\t\"startDate\": 27032018,\n" +
"\t\"endDate\": 27032018,\n" +
"\t\"machineOwner\": \"Nilesh\",\n" +
"\t\"description\": \"good\",\n" +
"\t\"status\": \"working\"\n" +
"}, ...
"}]";
JSONArray array= null;
JSONArray filter=new JSONArray();
try {
//change res to a JsonArray object so i can filter
array = new JSONArray(res);
try {
for (int i=0; i<array.length();i++){
String date=array.getJSONObject(i).has("startDate")?array.getJSONObject(i).getString("startDate"):"";
//if i match selected date i pick it
if (!TextUtils.isEmpty(date)&&date.equals(dateselected))
filter.put(array.getJSONObject(i));
}
}catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
//res
res=filter.toString();
return new Gson().fromJson(res, new TypeToken<List<ScheduledTasks>>() {
}.getType());
}

Concatenation inside try catch

try {
final List<NetworkType> dataReceived = getData();
int i = 0;
//Array Iteration
for(final NetworkType networkType : dataReceived) {
i++;
if (i > 3) {
Toast.makeText(getApplicationContext(), "Done!!", Toast.LENGTH_SHORT);
} else {
String mCell1CID = networkType.getCell1CID();
String mCell1LAC = networkType.getCell1LAC();
String mCell1MCC = networkType.getCell1MCC();
String mCell1MNC = networkType.getCell1MNC();
String mCell1CI = networkType.getCell1CI();
String mCell1TAC = networkType.getCell1TAC();
//API requestBody
String url = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyA8NAA3dUpECFn2j6pdcQT3wgqUM98UZ2Q";
String cellID = null;
String locationAreaCode = null;
if (mCell1CID.equals("") && mCell1LAC.equals("")) {
cellID = mCell1CI;
locationAreaCode = mCell1TAC;
} else if (mCell1CI.equals("") && mCell1TAC.equals("")) {
cellID = mCell1CID;
locationAreaCode = mCell1LAC;
} else {
Log.d("GeoL", "3");
}
String requestBody =
"{" +
"\"cellTowers\":[" +
"{" +
"\"cellId\" :" + cellID + "," +
"\"locationAreaCode\" :" + locationAreaCode + "," +
"\"mobileCountryCode\" :" + "\"" + mCell1MCC + "\"" + "," +
"\"mobileNetworkCode\" :" + "\"" + mCell1MNC + "\"" +
"}" +
"]" +
"}";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(String.valueOf(response));
JSONObject latitude = jsonObject.getJSONObject("location");
String lat = latitude.getString("lat");
String lng = latitude.getString("lng");
String acc = jsonObject.getString("accuracy");
if (!dataReceived.listIterator().hasNext()){
String print;
print = String.format("%s%s", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
} else {
String print;
print = String.format("%s%s,", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response", "error" + error.toString());
}
});
queue.add(jsObjRequest);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I need to concat the received value to the print variable.
But this the error which i receive
print needs to be initialized is what I receive.
also if declared outside the try/catch block it requires it to be final.
What to do?
just use String print = null; when you declare print
You are providing a value that is not initialized to the String.format
You need to initialize the variable "print" with what you want to be used in the String.format (for example an empty String) :
String print= ""
Or use String Builder:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("1");
stringBuilder.append("2");
String finalString = stringBuilder.toString();

Android: JSONException: Value null at VesselList of type org.json.JSONObject$1 cannot be converted to JSONArray

I'trying to Parsing JSOn object but sometime it runs properly sometime getting followoing error:
org.json.JSONException: Value null at VesselList of type
org.json.JSONObject$1 cannot be converted to JSONArray
public void getCompanyDeatails()
{
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/"+strSync_Time+"/Authentication_Token/"+str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(strUrl_companyDeatls));
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
strResult = convertInputStreamToString(inputStream);
else
strResult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
String jsonStr = strResult;
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null)
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString());
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
str_CompanyId = jobCompanyDetails.getString("Company_ID");
str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
if (dbhelper.isTitleExist(str_CompanyId)) {
//Upadte
dbhelper.updatedetails(str_CompanyId, str_CompanyName);
Log.e("Data updated in ", "Company Table !!");
} else {
//insert
dbhelper.insertCompany(str_CompanyId, str_CompanyName);
Log.e("Data inserted in ", "Company Table !!");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
this is my JSON String
{"Get_CompanyResult":{"CompanylList":[{"Company_ID":93,"Company_Name":"SeaChange"},{"Company_ID":97,"Company_Name":"VM 2"}],"Sync_Time":"2015-09-11 12:44:17.533"}}
Is this code is right?
Here:
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
line causing issue because CompanylList JSONArray is inside Get_CompanyResult JSONObject instead of main which is jsonObj.
Get CompanylList JSONArray from companyList JSONObject:
JSONArray jarr = companyList.getJSONArray("CompanylList");
Change your code according to here :
public void getCompanyDeatails() {
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/" + strSync_Time + "/Authentication_Token/" + str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
String strResult = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet("strUrl_companyDeatls"));
inputStream = httpResponse.getEntity().getContent();
// strResult = "{\\\"Get_CompanyResult\\\":{\\\"CompanylList\\\":[{\\\"Company_ID\\\":93,\\\"Company_Name\\\":\\\"SeaChange\\\"},{\\\"Company_ID\\\":97,\\\"Company_Name\\\":\\\"VM 2\\\"}],\\\"Sync_Time\\\":\\\"2015-09-11 12:44:17.533\\\"}}";
String jsonStr=null;
if (inputStream != null) {
strResult = convertInputStreamToString(inputStream);
jsonStr = strResult;
}
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null) {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = companyList.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString()); // error was here. You need to use companyList json object because it contains company list.
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
String str_CompanyId = jobCompanyDetails.getString("Company_ID");
String str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
// if (dbhelper.isTitleExist(str_CompanyId)) {
// //Upadte
// dbhelper.updatedetails(str_CompanyId, str_CompanyName);
// Log.e("Data updated in ", "Company Table !!");
// } else {
//
// //insert
// dbhelper.insertCompany(str_CompanyId, str_CompanyName);
// Log.e("Data inserted in ", "Company Table !!");
// }
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Note :
There is no need to use nested try and catch.
For 'strResult = "Did not work!";', always make sure that every
exception handled well (at checkpoint of jsonstr is null or not you
can not identify error occurred at parsing input stream can lead to
serious bugs).
HttpClient is deprecated so make sure you use latest version of any
third party library like Volley or Retrofit for network
operation and GSON for parsing response. It will minimize your
efforts.
Thanks.

How do I structure my data to switch from using ParseJsonArray/ParseJsonObject to using GSON.fromJson(...)

I have been working with GSON to try and parse a Json response I am getting from a CakePHP server for about a week. Here is what the response looks like :
[{"BaseObject": {"field1":"1","field2":"1639","field3":"10","field4":"1","field5":"12","field6":"10.765984","field7":"-25.768357","field8":"1327790850"}},{"BaseObject":{"field1":"2","field2":"1934","field3":"19","field4":"30","field5":"2","field6":"10.758662","field7":"-25.769684","field8":"1327790850"}},{"BaseObject":{"field1":"3","field2":"2567","field3":"33","field4":"6","field5":"98","field6":"10.758786","field7":"-25.769843","field8":"1327790850"}},{"BaseObject":{"field1":"4","field2":"0","field3":"33","field4":"7","field5":"0","field6":"10.758786","field7":"-20.769843","field8":"1327790850"}},{"BaseObject":{"field1":"5","field2":"1097","field3":"33","field4":"1","field5":"0","field6":"15.758786","field7":"50.769843","field8":"1327790850"}},{"BaseObject":{"field1":"6","field2":"1936","field3":"50","field4":"0","field5":"9","field6":"19.234987","field7":"-67.340065","field8":"1327798560"}}]
I used a plugin for Notepad++ to verify that the response is valid Json and it is.
First I tried this function:
public static List<BaseObject> parserInputStreamGson(InputStream stream)
{
List<BaseObject> objList = new ArrayList<BaseObject>();
if(stream != null){
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG,"Trying to Parse Reader");
try{
objList = gson.fromJson(r, new TypeToken<List<BaseObject>>() {}.getType() );
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage() );
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage() );
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage() );
}
}
}
Log.d(TAG,"BaseObject[] = " + objList.toString());
return objList;
}
Then I tried this function:
public static BaseObject[] parserInputStreamGsonArray(InputStream stream)
{
BaseObject[] objectArray = null;
if (stream != null) {
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG, "Trying to Parse Reader");
try {
objectArray = gson.fromJson(r, new TypeToken<Event[]>() {}.getType());
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage());
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage());
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage());
}
}
}
if(eventArray != null){
for(int m=0;m<eventArray.length;m++){
Log.d(TAG, "objectArray[" + String.valueOf(m) + "] = " + objectArray[m].toString());
}
}
return objectArray;
}
And in both cases Gson returned 5 objects, but all of the fields were set to zero.
Finally I got this function to work, but it feels clunky.
public static List<BaseObject> ParseInputStream(InputStream stream) {
Reader r = new InputStreamReader(stream);
List<BaseObject> baseObjectList = new ArrayList<BaseObject>();
try {
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(r).getAsJsonArray();
JsonObject topObject = new JsonObject();
JsonObject subObject = new JsonObject();
for (int m = 0; m < array.size(); m++) {
if (array.get(m).isJsonObject()) {
topObject = array.get(m).getAsJsonObject();
if (topObject.get("BaseObject").isJsonObject()) {
subObject = topObject.get("BaseObject").getAsJsonObject();
BaseObject baseobject = new BaseObject();
baseobject.field1 = subObject.get("field1").getAsLong();
baseobject.field2 = subObject.get("field2").getAsInt();
baseobject.field3 = subObject.get("field3").getAsLong();
baseobject.field4 = subObject.get("field4").getAsInt();
baseobject.field5 = subObject.get("field5").getAsInt();
baseobject.field6 = subObject.get("field6").getAsDouble();
baseobject.field7 = subObject.get("field7").getAsDouble();
baseobject.field8 = subObject.get("field8").getAsLong();
baseObjectList.add(baseobject);
} else {
Log.e(TAG, "topObject[" + String.valueOf(m)+ "].subObject is not a JsonObject");
}
} else {
Log.e(TAG, "Array # " + String.valueOf(m)+ " is not a JsonObject!");
}
}
} catch (Exception ex) {
Log.e(TAG, "Exception thrown = " + ex.toString());
ex.printStackTrace();
}
return baseObjectList;
}
Here is the class I created for BaseObject.
public class BaseObject {
#SerializedName("field1")
public long field1;
#SerializedName("field2")
public int field2;
#SerializedName("field3")
public long field3;
#SerializedName("field4")
public int field4;
#SerializedName("field5")
public int field5;
#SerializedName("field6")
public double field6;
#SerializedName("field7")
public double field7;
#SerializedName("field8")
public long field8;
#Override
public String toString() {
return "(" +
"field1= " + String.valueOf(this.field1) + ", " +
"field2= " + String.valueOf(this.field2) + ", " +
"field3= " + String.valueOf(this.field3) + ", " +
"field4= " + String.valueOf(this.field4) + ", " +
"field5= " + String.valueOf(this.field5) + ", " +
"field6= " + String.valueOf(this.field6) + ", " +
"field7= " + String.valueOf(this.field7) + ", " +
"field8= " + String.valueOf(this.field8) +
")";
}
}
Can anyone tell me how I need to structure my data classes in order use Gson.fromJson to work.
Since your response is actually List<BaseObject>, you should be using
List baseObjectList = new Gson().fromJson(r,new TypeToken>() {}.getType())
Also I should mention that, you do not really need to use the #SerializedName annotations since your attribute names in the json reply and in the class are same.
UPDATE:
Oops.. Sorry, I should have tried your code before answering. Please refer to the following code. Everything boiled down to the Structuring of classes.
public class Sample {
public static class Wrapper{
private BaseObject BaseObject;
#Override
public String toString() {
return BaseObject == null? null : BaseObject.toString();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String json = "[{\"BaseObject\": {\"field1\":\"1\",\"field2\":\"1639\",\"field3\":\"10\",\"field4\":\"1\",\"field5\":\"12\",\"field6\":\"10.765984\",\"field7\":\"-25.768357\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"2\",\"field2\":\"1934\",\"field3\":\"19\",\"field4\":\"30\",\"field5\":\"2\",\"field6\":\"10.758662\",\"field7\":\"-25.769684\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"3\",\"field2\":\"2567\",\"field3\":\"33\",\"field4\":\"6\",\"field5\":\"98\",\"field6\":\"10.758786\",\"field7\":\"-25.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"4\",\"field2\":\"0\",\"field3\":\"33\",\"field4\":\"7\",\"field5\":\"0\",\"field6\":\"10.758786\",\"field7\":\"-20.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"5\",\"field2\":\"1097\",\"field3\":\"33\",\"field4\":\"1\",\"field5\":\"0\",\"field6\":\"15.758786\",\"field7\":\"50.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"6\",\"field2\":\"1936\",\"field3\":\"50\",\"field4\":\"0\",\"field5\":\"9\",\"field6\":\"19.234987\",\"field7\":\"-67.340065\",\"field8\":\"1327798560\"}}]";
List<Wrapper> results = new Gson().fromJson(json,new TypeToken<List<Wrapper>>(){}.getType());
System.out.println(results);
}
}
Just curious, do you have the liberty to change the JSON reply coming from server? IMHO, Its structure is a little complicated.

Categories

Resources