AsyncTask with Multiple JsonRequest - android

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.

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 org.json.JSONArray cannot be converted to JSONObject (can not display the url)

I am new in android I work on a webservice application and the backend in laravel ,I want to read the trades and according to the job I find the tasks but I can not display the data it shows me this error msg ..
"org.json.JSONArray cannot be converted to JSONObject"
public static final String TacheNamearray = "libelle_tache";
public static final String TacheName = "libelle_tache";
public static final String JSON_ARRAY_TACHE = "result";
public static final String MetierNamearray = "libelle_metier";
public static final String MetierName = "libelle_metier";
public static final String JSON_ARRAY = "result";
private JSONArray result;
private ArrayList<String> arrayListTache;
TextView tacheename;
Spinner spinner_tache;
Spinner spinner;
Button button;
private GpsTracker gpsTracker;
private TextView tvLatitude,tvLongitude;
String URL_Post = "http://192.168.1.233/projet/public/api/getmetier";
private ArrayList<String> arrayList;
TextView employeename;
private TextView tvUsername, tvEmail;
private UserInfo userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recherche);
spinner= (Spinner) findViewById(R.id.spnrEmployee);
spinner_tache= (Spinner) findViewById(R.id.spnrTache);
tacheename= (TextView) findViewById(R.id.tvTache);
employeename= (TextView) findViewById(R.id.tvName);
button = (Button) findViewById(R.id.button);
tvLatitude = (TextView)findViewById(R.id.latitude);
tvLongitude = (TextView)findViewById(R.id.longitude);
arrayListTache = new ArrayList<String>();
userInfo = new UserInfo(this);
tvEmail = (TextView)findViewById(R.id.key_email);
String email = userInfo.getKeyEmail();
tvEmail.setText(email);
arrayList = new ArrayList<String>();
getMetiers();
spinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
//Setting the values to textviews for a selected item
String metier= arrayList.get(position);
getTaches(metier);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
employeename.setText("");
}
});
}
private void getMetiers() {
StringRequest stringRequest = new
StringRequest("http://192.168.1.233/projet/public/api/getmetier",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
empdetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void empdetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayList.add(json.getString(MetierNamearray));
} catch (JSONException e) {
e.printStackTrace();
}
}
// arrayList.add(0,"Select Employee");
spinner.setAdapter(new ArrayAdapter<String>(RechercheActivity.this,
android.R.layout.simple_spinner_dropdown_item, arrayList));
}
//Method to get student name of a particular position
private String getemployeeName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(MetierName);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
public void getLocation(View view){
gpsTracker = new GpsTracker(RechercheActivity.this);
insert();
if(gpsTracker.canGetLocation()){
double latitude = gpsTracker.getLatitude();
double longitude = gpsTracker.getLongitude();
tvLatitude.setText(String.valueOf(latitude));
tvLongitude.setText(String.valueOf(longitude));
}else{
gpsTracker.showSettingsAlert();
}
Intent intent = new Intent(RechercheActivity.this,
TechnicienActivity.class);
startActivity(intent);
}
public void insert(){
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_Post, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplication(),response,Toast.LENGTH_LONG).show();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RechercheActivity.this,error+"",Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String,String>getParams()throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
String text1 = spinner.getSelectedItem().toString();
String lon = tvLongitude.getText().toString().trim();
String lat = tvLatitude.getText().toString().trim();
params.put("libelle_metier",text1);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getTaches(String metier) {
StringRequest stringRequest = new
StringRequest("http://192.168.1.233/projet/public/api/gettaches",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result= j.getJSONArray(JSON_ARRAY_TACHE);
tachedetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void tachedetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayListTache.add(json.getString(TacheNamearray));
} catch (JSONException e) {
e.printStackTrace();
}
// arrayListTache.add(0,"Select Employee");
spinner_tache.setAdapter(new ArrayAdapter<String>
(RechercheActivity.this,
android.R.layout.simple_spinner_dropdown_item, arrayListTache));
}
//Method to get student name of a particular position
private String gettacheName(int position){
String libelle_tache="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
libelle_tache = json.getString(TacheName);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return libelle_tache;
}
and the JSON part gives me that ..
[{"id":1,"libelle_metier":"metier 1","deleted_at":null,"created_at":"2018-04-03 09:12:37","updated_at":"2018-04-03 09:12:37"},{"id":2,"libelle_metier":"metier 2","deleted_at":null,"created_at":"2018-04-03 09:12:44","updated_at":"2018-04-03 09:12:44"},{"id":3,"libelle_metier":"metier 4","deleted_at":null,"created_at":"2018-04-03 09:46:36","updated_at":"2018-04-04 14:15:06"}]
and my PHP code and
class TechniciensController extends Controller
{
public function GetTechniciens()
{
return Technicien::all();
}
return json_encode(Technicien::all());
then you can use json_decode.
this line :
j = new JSONObject(response);
update it:
JSONArray jsonarray = new JSONArray(response);
i think it's works.

My app crashes when there is no value in my JSON

I'm posting "id" value (which i pass to this activity via getintent)
Uid = getIntent().getStringExtra("id");
to server and retrieving the corresponding jsonobjects.
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
When my jsonarray is empty, my app crashes. I want to toast"Error" when jsonarray is empty. How can I fix this?
Here is my code:
public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(kill.this);
pDialog.setMessage("Loading...");
pDialog.show();
//fetching JSONArray
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
}
apply the check in onResponse
if(response.length()==0){
// error message
}else{
// your rest of the code
}
This looks problematic.
Datas.imageIds = new String[response.length()];
You don't want an array with the size of the string. You want an array of the size of the JSONArray within the response.
public void onResponse(String response) {
JSONArray arr = null;
try {
arr = new JSONArray(response);
Datas.imageIds = new String[arr.length()];
} catch (JSONException e1) {
e1.printStackTrace();
}
However, your code is going to continue on if an exception is thrown there, then you'll end up with a NullPointerException, so you should move the for-loop into the try-catch as well.
Realistically, though, you should just use a JSONArrayRequest if you're going to be expecting a JSONArray.
i want to toast"Error" when jsonarray is empty
Simple enough.
arr = new JSONArray(response);
if (arr.length() == 0) {
// TODO: Toast
}
I would simply add two checks to your onResponse method:
...
public void onResponse(String response) {
// Check if the response itself is an empty string or null
if(TextUtils.isEmpty(response)) {
// Show your user feedback
return;
}
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
// Check if your JSON has no elements in it
if(arr.length == 0) {
// Show your user feedback
return;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
...
You have declared JSONArray arr = null;
After that you assign the server's JSON to that JSONArray.
Add a line after getting that
if(arr==null)
{
//toast
}
else
{
//whatever you want to do with JSON
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.length()==0){
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
else{
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
if(arr.length()>0){
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
}else{
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
}
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
Use the below code to check whether response is null or not and in object check whether it is having key or data with key is not null
if(response!=null){
try {
Datas.imageIds = new String[response.length()];
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
if(obj!=null){
if(obj.has("category_name") && !obj.isNull("category_name"){
category = obj.getString("category_name");
}
if(obj.has("album_id") && !obj.isNull("album_id"){
selected = obj.getString("album_id");
}
if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
imagename = obj.getString("org_image_name");
}
if(obj.has("album_image") && !obj.isNull("album_image"){
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
You are using StringRequest, instead of that use JsonArrayRequest to make request as below, so you will get response in onResponse methode when there is a valid JSONArray in response, and if there is no data then you will get response in onError method
JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,"url", new JSONObject(), new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error.getMessage() );
}
})

Android: Updating List within volley

I want to fill a list of items from the internet. For that I am using volley. If I add values to the list manually, it works:
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
for (int i = 0; i < 6; i++) {
Bitmap b = null;
ImageItem imageItem = new ImageItem();
imageItem.setImageFromDB("http://192.168.192.200/images/q112898055d4-eb4d-41ef-9c00-0069789740c1.jpg");
imageItems.add(imageItem);
}
return imageItems;
}
But if I use volley, it doesn't work.. The list is empty. In addition to that I have this list for a gridview-adapter. Here is my code with volley:
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
final String url = "http://192.168.192.200/getCustomerQuotes.php?9tEqRp93s2t&EsAzJo1EtNM&VuEtfRAPjNU&NTv5hhlsx5Y&uid=112";
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("TAB1ZZ", "url is " + url);
VolleyLog.d("LIKES", "Response: " + response.toString());
if (response != null) {
try {
JSONArray arr = response.getJSONArray("feed");
for (int i = 0; i < 5; i++) {
JSONObject obj = arr.getJSONObject(i);
String imageForDb = StaticVariables.baseUrlForImage + obj.getString("imageName");
Log.e("IAMGEFODB", "is " + imageForDb);
ImageItem imageItem = new ImageItem();
imageItem.setImageFromDB(imageForDb);
imageItems.add(imageItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
return imageItems;
}

Volley Object request Returning 0

I Have a Remote Database that contains 6 rows.
Here's my code, I put it in List so that i can get the size,
But it's always returning 0.
public List<Comments> getComments() {
final List<Comments> commentsData = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleyHelper.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
return commentsData;
}
I need the size for some use.
Why is it always returning zero?
I even tried adding a counter++ inside for loop.
But when i get the value of the counter its still zero.
JsonObjectRequest run on a background thread. That's why you getting the list size 0. you must work into the public void onResponse(JSONObject response) {} function .
Exmp.
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
// **you may call function and pass the list value to update your ui component. you will get the real size of list here.**
} catch (JSONException e) {
e.printStackTrace();
}
}

Categories

Resources