Android query can't store class variable from JSON object callback - android

I can't write class variable from AJAX-JSON callback. It show right info inside callback but when a Query callback finishes, it is set to null. Why?
This is code:
public void asyncJson() {
String url = "myurl";
aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status
{
if (json != null) {
jsonToString(json);
} else {
Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
}
}
});
private void jsonToString(JSONObject data) {
JSONArray array = null;
try {
array = data.getJSONArray("listResp");
for (int i = 0; i < array.length(); i++) {
JSONObject json_data = array.getJSONObject(i);
c.setDate_creation(json_data.getString("date_creation"));
c.setName_user(json_data.getString("name_user"));
list.add(c);//linkedlist
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
The variable listContest when callback finishes is null.

Related

How parse JSON data into ListView

I would like to visualize the Json data on a listview, but I don't know how to do it ... I tried to use a TextView to verify the correct passage of the data and it seems to work, but I would need to display them on the listView ... ideas?
{"Esito":true,"Dati":[{"id":"357","id_utente":"16","nome_prodotto":"cozze"},{"id":"358","id_utente":"16","nome_prodotto":"riso"},{"id":"362","id_utente":"16","nome_prodotto":"patate"},{"id":"366","id_utente":"16","nome_prodotto":"cozze"},{"id":"367","id_utente":"16","nome_prodotto":null}]}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.G[enter image description here][1]ET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Dati");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dato = jsonArray.getJSONObject(i);
String id = dato.getString("id");
String id_utente = dato.getString("id_utente");
String nome_prodotto = dato.getString("nome_prodotto");
mTextViewResult.append(id + ", " + id_utente + ", " + nome_prodotto + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Just make new object class and collect data to list :
class YourObiekt {
private String id;
private String idUtente;
private String nomeProdotto;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdUtente() {
return idUtente;
}
public void setIdUtente(String idUtente) {
this.idUtente = idUtente;
}
public String getNomeProdotto() {
return nomeProdotto;
}
public void setNomeProdotto(String nomeProdotto) {
this.nomeProdotto = nomeProdotto;
}
}
List<YourObiekt> yourObiektList = new ArrayList<YourObiekt>();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Dati");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dato = jsonArray.getJSONObject(i);
YourObiekt yo = new YourObiekt();
yo.setId(dato.getString("id"));
yo.setIdUtente(dato.getString("id_utente"));
yo.setNomeProdotto(dato.getString("nome_prodotto"));
yourObiektList.add(yo);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And now you get yourObiektList as data for your listView

Android - How to get JSON array in Child

I'm beginner in Android Studio, and I am a bit difficult to parse json data in Android, so I want to ask question about get or parsing JSON Child Array.
This is my Code :
public void resSuccess(String requestType, JSONObject response)
{ progressBar.setVisibility(View.GONE);
try {
token = response.getString("token");
JSONArray array = response.getJSONArray("all_airport");
for (int i=0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
JSONArray jsonArray = jsonObject.getJSONArray("airport");
for (int j=0; j<jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(j);
BandaraDataSet bds = new BandaraDataSet();
idDep = object.getString("country_id");
bds.setId(object.getString("id"));
bds.setAirport_name(object.getString("airport_name"));
bds.setAirport_code(object.getString("airport_code"));
bds.setCountry_name(object.getString("country_name"));
bds.setCountry_id(object.getString("country_id"));
bds.setLocation_name(object.getString("location_name"));
list.add(bds);
}
}
bandaraAdapter = new BandaraAdapter(ActivityPesawat.this, list);
bandaraAdapter.notifyDataSetChanged();
listBandara.setAdapter(bandaraAdapter);
} catch (Exception e){
e.printStackTrace();
}
}
And This is my Json
{
"all_airport":{
"airport":[
{
"airport_name":"Mali",
"airport_code":"ARD",
"location_name":"Alor Island",
"country_id":"id",
"country_name":"Indonesia"
},
{
"airport_name":"Pattimura",
"airport_code":"AMQ",
"location_name":"Ambon",
"country_id":"id",
"country_name":"Indonesia"
},
{
"airport_name":"Tanjung Api",
"airport_code":"VPM",
"location_name":"Ampana",
"country_id":"id",
"country_name":"Indonesia"
}
]
},
"token":"ab4f5e12e794ab09d49526bc75cf0a0139d9d849",
"login":"false"
}
so my problem when Parse Json is null in Android, please help anyone..
You are handling the JSONObject as if it were a JSONArray. Try this code:
public void resSuccess(String requestType, JSONObject response) {
progressBar.setVisibility(View.GONE);
try {
token = response.getString("token");
JSONObject airports = response.getJSONObject("all_airport");
JSONArray airportArray = airports.getJSONArray("airport");
for (int j = 0; j < airportArray.length(); j++) {
BandaraDataSet bds = new BandaraDataSet();
JSONObject object = airportArray.getJSONObject(j);
idDep = object.getString("country_id");
bds.setId(object.getString("id"));
bds.setAirport_name(object.getString("airport_name"));
bds.setAirport_code(object.getString("airport_code"));
bds.setCountry_name(object.getString("country_name"));
bds.setCountry_id(object.getString("country_id"));
bds.setLocation_name(object.getString("location_name"));
list.add(bds);
}
bandaraAdapter = new BandaraAdapter(ActivityPesawat.this, list);
bandaraAdapter.notifyDataSetChanged();
listBandara.setAdapter(bandaraAdapter);
} catch (Exception e){
e.printStackTrace();
}
}
You should proper json parsing or you can use Gson(library) for json parsing. You just need to have proper Model(Bean) classes. And then parsing will be too easy.
compile 'com.google.code.gson:gson:2.7'
Create below Model/Bean classes
import java.io.Serializable;
//Response.java
public class Response implements Serializable {
AllAirPort all_airport;
public AllAirPort getAll_airport() {
return all_airport;
}
public void setAll_airport(AllAirPort all_airport) {
this.all_airport = all_airport;
}
}
//AllAirPort.java
public class AllAirPort implements Serializable{
ArrayList<AirportModel> airport;
public ArrayList<AirportModel> getAirport() {
return airport;
}
public void setAirport(ArrayList<AirportModel> airport) {
this.airport = airport;
}
}
//AirportModel.java
public class AirportModel implements Serializable {
String airport_name;
String airport_code;
String location_name;
String country_id;
String country_name;
public String getAirport_name() {
return airport_name;
}
public void setAirport_name(String airport_name) {
this.airport_name = airport_name;
}
public String getAirport_code() {
return airport_code;
}
public void setAirport_code(String airport_code) {
this.airport_code = airport_code;
}
public String getLocation_name() {
return location_name;
}
public void setLocation_name(String location_name) {
this.location_name = location_name;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
public String getCountry_name() {
return country_name;
}
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
}
Response responseObject = new Gson().fromJson(yourstringResponse, Response.class);
now you can start getting data from responseObject.

E/Volley: [33049] BasicNetwork.performRequest: Unexpected response code 404

I am using RecyclerView to display data fetched from DB. It's not working.
GETTING AN ERROR E/Volley: [33049] BasicNetwork.performRequest: Unexpected response code 404.
Need to parse below Response:-
[
{
"code":"23232",
"desc":"ddddjdkdkcn",
"price":[
"price"
]
},
{
"code":"de33fd",
"desc":"ddds",
"price":[
"price"
]
}
]
public class Background {
String url = "http://192.168.0.103/android_fetch.php";
Context context;
ArrayList<Data> arrayList = new ArrayList<>();
public Background(Context context) {
this.context = context;
}
public ArrayList<Data> getList() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, (String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
Data data = new Data(jsonObject.getString("code"), jsonObject.getString("desc"), jsonObject.getString("price"));
arrayList.add(data);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestque(jsonArrayRequest);
return arrayList;
}
}
First check your request in Postman . There is some error at back-end php side. After that your parsing method is also wrong .
There is mistake in this line i think .
Data data = new Data(jsonObject.getString("code"), jsonObject.getString("desc"), jsonObject.getString("price"));
here you try to get all as jsonObject but last price is JSONArray .
Try this way .
#Override
public void onResponse(JSONArray jsonresponse) {
try {
Log.i("get response", "get response" + jsonresponse);
for (int i = 0; i < jsonresponse.length(); i++) {
JSONObject response = jsonresponse.getJSONObject(i);
String code = response.getString("code");
String desc = response.getString("desc");
if (response.getJSONArray("price") != null && response.getJSONArray("price").length() > 0) {
JSONArray priceArray = response.getJSONArray("price");
final int numberOfItemsInResp = priceArray.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
String price = priceArray.getString(j);
}
}
}
} catch (Exception e) {
Common.ProgressDialogDismiss();
e.printStackTrace();
}
}

How to access object>array>object>array>object in json?

I have to fetch text via json in url .
The hierarchy is given below :
object>array>object>array>object.
I want to get text with this code .But I am getting error :org.json.JSONException: No value for text
Below is the code :-
public class ListViewActivity extends Activity {
// Log tag
private static final String TAG = ListViewActivity.class.getSimpleName();
// change here url of server api
private static final String url = "http://2e9b8f52.ngrok.io/api/v1/restaurants?per_page=5&km=1&location=true&lat=19.0558306414&long=72.8339840099";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = movieList.get(position);
Intent intent = new Intent(ListViewActivity.this, SecondActivity.class);
intent.putExtra("name", movie.getName());
intent.putExtra("average_ratings", movie.getAverage_ratings());
intent.putExtra("full_address", movie.getAddress());
intent.putExtra("image_url", movie.getThumbnailUrl());
intent.putExtra("cuisine",movie.getCuisine());
intent.putExtra("cost",movie.getCost());
startActivity(intent);
}
});
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Please Keep patience.Its loading...");
pDialog.show();
// Creating volley request obj
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray
restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
//movie.setThumbnailUrl(obj.getString("image"));
movie.setThumbnailUrl(obj.getString("org_image_url"));
movie.setAverage_ratings(obj.getString("average_ratings"));
movie.setCuisine(obj.getString("cuisine"));
movie.setAddress(obj.getJSONObject("address").getString("area"));
// movie.setAddress(obj.getJSONObject("address").getString("full_address"));
movie.setCost(obj.getString("cost"));
movie.setDistance( obj.getDouble("distance"));
movie.settext(obj.getString("text"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
I am attaching snapshot of json data. In the snapshot we can see the color "Text=15% discount on bill " i have to access .
try {
String yourresponseString ="";// this string refer to your api response
JSONObject jsonObject = new JSONObject(yourresponseString);
JSONArray objJsonArray = new JSONArray(jsonObject.getString("restaurants"));
for (int i = 0; i < objJsonArray.length(); i++) {
JSONArray objInnerJsonArray = objJsonArray.getJSONObject(i).getJSONArray("restaurant_offers");
for (int j = 0; j < objInnerJsonArray.length(); j++) {
//Here you can acess youe bill discount value
JSONObject objInnerJSONObject = objInnerJsonArray.getJSONObject(j);
System.out.println("Discount==>" + objInnerJSONObject.getString("text"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You can parse like this.And using this classes you can parse any type of hierarchy.
JSONArray restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
JSONArray textJSONArray= obj.getJSONArray("restaurant_offers");
for (int j = 0; j < textJSONArray.length(); j++) {
JSONObject txtobj =textJSONArray.getJSONObject(i);
movie.settext(txtobj .getString("text"));
}
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
try this code restaurant_offers is a JSONArray so you can parse like this
You can parse like this
JSONObject apiResponseJsonObject= // Your API Response
try {
JSONArray restaurantJSONArray = apiResponseJsonObject.getJSONArray("restaurants");
// you can get any text from an object like this
restaurantJSONArray.getJSONObject(index).getString("name");
restaurantJSONArray.getJSONObject(index).getString("cost"); // Like this
//If you want to access phone numbers of specific object
JSONArray phoneJSONArray=restaurantJSONArray.getJSONObject(index).getJSONArray("phone_numbers");
// And you can get specific data from phoneNumber like this
phoneJSONArray.getJSONObject(phoneNumberIndex).getString("number");
//TO get Address, you can use like this
JSONObject addressJSONObject=restaurantJSONArray.getJSONObject(index).getJSONObject("address");
//Like this you can parse whatever you want.
} catch (JSONException e) {
e.printStackTrace();
}
You must change the for loop content like this
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
JSONArray restauranstOffersJSONArray = obj.getJSONArray("restaurants_offers");
for (int i = 0; i < restauranstOffersJSONArray.length(); i++) {
JSONObject offersObj = restauranstOffersJSONArray.get(i);
String text = offersObj.getString("text");
}

How to sort a jsonarray data by Date & Time and put in list view adapter

here my jsonArray data like:
[{"LeadId":4,
"CoreLeadId":0,
"CompanyId":7,
"AccountNo":"5675",
"ScheduleOn":"2015-05-11T00:00:00"},
{"LeadId":7,
"CoreLeadId":2,
"CompanyId":8,
"AccountNo":"sample string 4",
"ScheduleOn":"2015-12-01T15:04:23.217"}]
i want to sort by dateandtime(ScheduleOn) and put into listview. below i side i send snnipt of my code where i set adapter. can we sort into listItemService. Please help me.
JSONArray jsonArray = dpsFunctionFlow.getAllServiceDetail("1");
listItemService = new Gson().fromJson(jsonArray.toString(),
new TypeToken<List<AppointmentInfoDto>>() {
}.getType());
mAdapter = new AdapterAppointment(getActivity(), listItemService);
listView.setAdapter(mAdapter);
You should be able to use Collections.sort(...) passing in a Comparator that will compare 2 AppointmentInfoDto objects.
Collections.sort(listItemService, new Comparator<AppointmentInfoDto>() {
#Override public int compare(AppointmentInfoDto l, AppointmentInfoDto r) {
// Compare l.ScheduleOn and r.ScheduleOn
}
}
/// Sort JSON By any Key for date
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return CompareString1.compareTo(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}
// _Sort JSON for any String Key value.........
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return isCase ? CompareString1.compareTo(CompareString2) : CompareString1.compareToIgnoreCase(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}

Categories

Resources