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
Related
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.
I have FB, Google and normal login in my app.when I log in with FB or google everything is fine, but whenever I signup from the app and sign in instantly I am not getting data in CartActivity RecyclerView, but data is showing in postman or browser.Again when I uninstall the app and reinstall data start showing that old login credentials.
CartActivity:
try {
StringRequest stringRequest = new StringRequest(Request.Method.GET, url2,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.dismiss();
// Toast.makeText(CartActivity.this, "responce"+response.toString(), Toast.LENGTH_SHORT).show();
System.out.println("Response is : " + response);
try {
JSONObject jsono = new JSONObject(response);
if (jsono.getString("status").equals("success")) {
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
String total = object.getString("cart_total");
jarray = jsono.getJSONArray("data");
JSONArray jarray1 = object.getJSONArray("product_description");
for (int j = 0; j < jarray1.length(); j++) {
JSONObject object1 = jarray1.getJSONObject(j);
JSONArray jarray2 = object1.getJSONArray("data");
for (int k = 0; k < jarray2.length(); k++) {
JSONObject object2 = jarray2.getJSONObject(k);
String Name = object2.getString("product_name");
String Image = object2.getString("product_image");
String Price = object2.getString("product_price");
String Qty = object2.getString("product_qty");
String sku = object2.getString("product_sku");
String ProId = object2.getString("product_id");
System.out.println("VALUES: " + Name + "price" + Price + "qty" + Qty + sku + "proid" + ProId);
}
}
}
rccart.setAdapter(cartAdapter);
cartAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "Something went wrong...", Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
System.out.println("EXCPTION IN SUCCESS REQUEST : " + ex.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.dismiss();
System.out.println("ERROR IN REQUEST : " + error.getMessage());
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(CartActivity.this);
requestQueue.add(stringRequest);
pd = new ProgressDialog(CartActivity.this);
pd.setMessage("Loading...");
pd.show();
} catch (Exception ex) {
}
}
make one pojo class that define all the field if you getting at a response time like below code..
public class DataClass {
String Name ;
String Image ;
String Price ;
String Qty ;
String sku ;
String ProId;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
public String getQty() {
return Qty;
}
public void setQty(String qty) {
Qty = qty;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getProId() {
return ProId;
}
public void setProId(String proId) {
ProId = proId;
}
}
Add list in recycler view adapter like ....
private List<DataClass> mDataList=new ArrayList<>();
public CustomAdapter(List<DataClass> mDataList) {
this.mDataList = mDataList;
}
then after get response data to add into array list and pass into adapter..
private List<DataClass> mListData=new ArrayList<>();// define in type-array in your pojo class name
for (int k = 0; k < jarray2.length(); k++) {
JSONObject object2 = jarray2.getJSONObject(k);
DataClass dataClass=new DataClass();
String Name = object2.getString("product_name");
String Image = object2.getString("product_image");
String Price = object2.getString("product_price");
String Qty = object2.getString("product_qty");
String sku = object2.getString("product_sku");
String ProId = object2.getString("product_id");
dataClass.setName(Name);
dataClass.setImage(Image);
dataClass.setPrice(Price);
dataClass.setQty(Qty);
dataClass.setSku(sku);
dataClass.setProId(ProId);
mListData.add(dataClass);
System.out.println("VALUES: " + Name + "price" + Price + "qty" + Qty + sku + "proid" + ProId);
}
if (!mListData.isEmpty()){
cartAdapter=new CartAdapter(mListData);
rccart.setAdapter(cartAdapter);
cartAdapter.notifyDataSetChanged();
}
Got the solution.That was happening because of cache. just cleared cache and problem solve.
JSON:
{
"videos":[
[
{
"video_id":"DKOLynNhWxo",
"video_url":"https:\/\/www.youtube.com\/watch?v=DKOLynNhWxo",
"video_host":"youtube",
"created_at":"2017-08-08 11:17:00",
"branch_name":"Computer Science",
"semester_name":"Semester 1",
"subject_name":"English"
},
{
"video_id":"haYm5k6h5yc",
"video_url":"https:\/\/www.youtube.com\/watch?v=haYm5k6h5yc",
"video_host":"Youtube",
"created_at":"2017-08-10 10:05:00",
"branch_name":"Computer Science",
"semester_name":"Semester 1",
"subject_name":"English"
}
],
[
{
"video_id":"VSkRU8eXFII",
"video_url":"https:\/\/www.youtube.com\/watch?v=VSkRU8eXFII",
"video_host":"youtube",
"created_at":"2017-08-08 11:18:00",
"branch_name":"Computer Science",
"semester_name":"Semester 1",
"subject_name":"Maths"
}
],
[],
[]
]
}
Code:
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(JsonExp.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
AppController sh = new AppController();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("videos");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
//JSONObject cjsnobj = contacts.getJSONObject(i);
JSONArray c = contacts.getJSONArray(i);
for (int y = 0; y < c.length(); y++)
{
JSONObject obj=c.getJSONObject(i);
String aid = obj.getString("video_id");
String url = obj.getString("video_url");
// String name = obj.getString("video_host");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("video_id", aid);
contact.put("video_url", url);
// contact.put("video_host", name);
// adding contact to contact list
contactList.add(contact);
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
JsonExp.this, contactList,
R.layout.list_item, new String[]{"video_id","video_url"//, "video_host"//, "ProductDetails", "rectimestamp"
}, new int[]{R.id.aid, R.id.name
});
lv.setAdapter(adapter);
}
}
replace JSONObject obj=c.getJSONObject(i); with JSONObject obj=c.getJSONObject(y);
I strongly suggest you to use Gson
The example:
Create a model class
public class Video {
private String id;
private String url;
private String host;
private String date;
private String branch;
private String semester;
private String subject;
public Video(String id, String url, String host, String date, String branch, String semester, String subject) {
this.id = id;
this.url = url;
this.host = host;
this.date = date;
this.branch = branch;
this.semester = semester;
this.subject = subject;
}
public String getId() {
return id;
}
public String getUrl() {
return url;
}
public String getHost() {
return host;
}
public String getDate() {
return date;
}
public String getBranch() {
return branch;
}
public String getSemester() {
return semester;
}
public String getSubject() {
return subject;
}
}
Create an arraylist
JSONArray contacts = jsonObj.getJSONArray("videos");
ArrayList<Video> videos = new ArrayList<>();
for (int i = 0; i < contacts.length(); i++) {
JSONObject contact = contacts.getJSONObject(i);
for (int y = 0; y < contact.length(); y++) {
JSONObject obj = contact.getJSONObject(y);
String id = obj.getString("video_id");
String url = obj.getString("video_url");
String host = obj.getString("video_host");
String date = obj.getString("created_at");
String branch = obj.getString("branch_name");
String semester = obj.getString("semester_name");
String subject = obj.getString("subject_name");
Video video = new Video(id, url, host, date, branch, semester, subject);
videos.add(video);
}
}
try{
JSONObject obj = nes JSONObject(yourResponse);
JSONArray video = obj.getJSONArray("videos");
for(i=0; i<video.length; i++){
JSONObject object = video.getJSONObject(i);
String subject_name = object.getString("subject_name");
}
}
catch(JSONException e){
}
I tried doing it multiple times using Volley library.
Link for JSON values: here
My android code to parse the values: here
public class GetUSGSjson extends AppCompatActivity
{
GridView jsonGridView;
ListView jsonListView;
Button jsonGetBtn;
RequestQueue USGSrequestqueue;
String USGSurl = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmag=6&limit=10";
ArrayList<String> mArrayList;
ArrayList<String>FK;
JsonObjectRequest USGSjsonObjectReq;
JSONObject _properties_;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.json_data);
jsonGridView = (GridView) findViewById(R.id.jsonGridView);
jsonGetBtn = (Button) findViewById(R.id.jsonGetBtn);
USGSrequestqueue = Volley.newRequestQueue(this);
mArrayList = new ArrayList<>();
FK = new ArrayList<>();
jsonGridView.setVisibility(View.GONE);
}
OnCllick of the button
public void USGSgetData(View view)
{
jsonGridView.setVisibility(View.VISIBLE);
USGSjsonObjectReq = new JsonObjectRequest(Request.Method.GET,USGSurl,null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try {
JSONObject _features_ = response.getJSONObject("features");
JSONArray _f_ = response.getJSONArray("features");
for (int x = 0; x < _f_.length(); x++)
{
JSONObject currentFeature = _f_.getJSONObject(x);
_properties_ = currentFeature.getJSONObject("properties"); //JsonObject
double mag = _properties_.getDouble("mag");
long time = _properties_.getLong("time");
String place = _properties_.getString("place");
mArrayList.add(String.valueOf(mag));
mArrayList.add(String.valueOf(time));
mArrayList.add(place);
ArrayAdapter VarrayAdapter = new ArrayAdapter<>(GetUSGSjson.this
,android.R.layout.simple_list_item_1, mArrayList);
jsonGridView.setAdapter(VarrayAdapter);
} catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(GetUSGSjson.this, "Exception: "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(GetUSGSjson.this, "onErrorResponse: "+error.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
USGSrequestqueue.add(USGSjsonObjectReq);
}
}
Try this,
try {
JSONArray arr_features=response.getJSONArray("features");
for(int i=0;i<arr_features.length();i++)
{
JSONObject obj=arr_features.getJSONObject(i);
String type=obj.getString("type");
JSONObject obj_properties=obj.getJSONObject("properties");
String mag=obj_properties.getString("mag");
String place=obj_properties.getString("place");
String time=obj_properties.getString("time");
String updated=obj_properties.getString("updated");
}
} catch (JSONException e) {
e.printStackTrace();
}
I found this way to solve my own problem
Remember that the "mag" is in double form "place" & "type" are in String form & "time" is a Unix time it's in long form.
try {
JSONArray _f_ = response.getJSONArray("features");
for (int x = 0; x < _f_.length(); x++)
{
JSONObject currentFeature = _f_.getJSONObject(x);
_properties_ = currentFeature.getJSONObject("properties"); //JsonObject
double mag = _properties_.getDouble("mag");
long time = _properties_.getLong("time");
String place = _properties_.getString("place");
String type = _properties_.getString("type");
// To add this on to ArrayList.
mArrayList.add("Place: "+place+"\n");
mArrayList.add("\nMagnitude: " + String.valueOf(mag)+"\n");
mArrayList.add("\nTime: " + String.valueOf(newTime)+"\n");
mArrayList.add("\nType: " + type+"\n");
}
When the app first run in the device I'm fetching the datas from the database and saved it to the SQLite so that the user can use it while offline.
My code is this.
public class AsyncDatas extends AsyncTask<Void,Void,Void> {
private Context context;
private List<ModelAccounts> accountDatas;
private List<ModelPoi> poiDatas;
private List<ModelComments> commentDatas;
private List<ModelImage> imageDatas;
private List<ModelFavorite> favoriteDatas;
final String MY_PREFS_NAME = "USER";
private List<ModelAccounts> accountDatas2;
private int count;
private Bitmap[] thumbnails;
private Activity activity;
public AsyncDatas(Context context,Activity activity){
this.context = context;
this.activity = activity;
}
#Override
protected Void doInBackground(Void... params) {
RequestQueue requestUsers = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectUsers = new JsonObjectRequest(Request.Method.POST,
GET_USER_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelAccounts modelAccounts = new ModelAccounts();
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getID = jsonObject.getInt("id");
accountDatas = new Select().from(ModelAccounts.class).where(Condition.column(ModelAccounts$Table.USER_ID).is(getID)).queryList();
if (accountDatas.size() == 0) {
modelAccounts = new ModelAccounts();
modelAccounts.setFname(jsonObject.getString("firstname"));
modelAccounts.setLname(jsonObject.getString("lastname"));
modelAccounts.setUname(jsonObject.getString("username"));
modelAccounts.setPword(jsonObject.getString("password"));
modelAccounts.setImg(jsonObject.getString("img"));
modelAccounts.setUser_id(String.valueOf(getID));
modelAccounts.save();
}
Log.e("DONE","DONE USEr");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestUsers.add(jsonObjectUsers);
RequestQueue requestFavorites = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectFav = new JsonObjectRequest(Request.Method.POST,
GET_FAV_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelFavorite modelFavorite = new ModelFavorite();
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getID = jsonObject.getInt("id");
favoriteDatas = new Select().from(ModelFavorite.class).where(Condition.column(ModelFavorite$Table.FAVORITE_ID).is(getID)).queryList();
if (favoriteDatas.size() == 0) {
modelFavorite = new ModelFavorite();
modelFavorite.setLatitude(jsonObject.getString("latitude"));
modelFavorite.setUser_id(jsonObject.getString("user_id"));
modelFavorite.setType(jsonObject.getString("type"));
modelFavorite.setFavorite_id(String.valueOf(getID));
modelFavorite.save();
}
}
Log.e("DONE","DONE FAV");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestFavorites.add(jsonObjectFav);
RequestQueue requestPOI = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectPOI = new JsonObjectRequest(Request.Method.POST,
INSERT_POI_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelPoi modelPoi = new ModelPoi();
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getID = jsonObject.getInt("id");
poiDatas = new Select().from(ModelPoi.class).where(Condition.column(ModelPoi$Table.POI_ID).is(getID)).queryList();
if(poiDatas.size()==0){
modelPoi = new ModelPoi();
modelPoi.setPOI(jsonObject.getString("POI"));
modelPoi.setPOIAddress(jsonObject.getString("POIAddress"));
modelPoi.setPOIType(jsonObject.getString("POIType"));
modelPoi.setPOILat(jsonObject.getString("POILat"));
modelPoi.setPOILong(jsonObject.getString("POILong"));
modelPoi.setPOIInfo(jsonObject.getString("POIInfo"));
modelPoi.setPoi_id(String.valueOf(getID));
modelPoi.save();
}
Log.e("DONE","DONE POI");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestPOI.add(jsonObjectPOI);
RequestQueue requestComments = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectComments = new JsonObjectRequest(Request.Method.POST,
COMMENTS_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelComments modelComments;
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getID = jsonObject.getInt("id");
commentDatas = new Select().from(ModelComments.class).where(Condition.column(ModelComments$Table.COMMENT_ID).is(getID)).queryList();
if (commentDatas.size() == 0) {
modelComments = new ModelComments();
modelComments.setLatitude(jsonObject.getString("latitude"));
modelComments.setComment_id(jsonObject.getString("id"));
modelComments.setComment(jsonObject.getString("comment"));
modelComments.setDate(jsonObject.getString("date"));
modelComments.setTitle(jsonObject.getString("title"));
modelComments.setUser_id(jsonObject.getString("user_id"));
modelComments.setRating(jsonObject.getString("rating"));
modelComments.setComment_id(String.valueOf(getID));
modelComments.save();
}
Log.e("DONE","DONE COMMENTS");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestComments.add(jsonObjectComments);
RequestQueue requestImage = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectImage = new JsonObjectRequest(Request.Method.POST,
GET_IMAGE_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelImage modelImage = new ModelImage();
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getId = jsonObject.getInt("id");
imageDatas = new Select().from(ModelImage.class).where(Condition.column(ModelImage$Table.IMAGE_ID).is(getId)).queryList();
if (imageDatas.size()==0) {
modelImage = new ModelImage();
modelImage.setLatitude(jsonObject.getString("latitude"));
modelImage.setImg(jsonObject.getString("imagepath"));
modelImage.setUser_id(jsonObject.getString("user_id"));
modelImage.setDatetime(jsonObject.getString("datetime"));
modelImage.setImage_id(String.valueOf(getId));
modelImage.save();
}
Log.e("DONE","DONE IMG");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestImage.add(jsonObjectImage);
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
Variable.IMAGES = new ArrayList<>();
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
context.getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
Variable.IMAGES.add("file://" + imagecursor.getString(dataColumnIndex));
Log.e("IMAGE","DOME IMAGE");
}
}
Sometimes it does work, Sometimes it doesn't.
Is there anyway to smoothen the process in the above codes?
Sometimes it work means, All datas fetch.
Sometimes it doesn't means, only fewdatas fetched.
Like only the first RequestQueue work..
Thanks.
You are doing to much work in one AsyncTask. Also for readability of the code, i recommend divide this code into smaller chunks perhaps one task for each API(web-service) call. then you will have all the data you need. decide the priority and then cal the tasks accordingly.