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();
}
}
Related
I am getting data on splash. I have almost 7k data that I am getting from the server. While getting data from the server I am saving it in the local database but the problem is the process is too slow. It almost takes 5 minutes. I want to resolve the problem. Please help.
Code to get data from server and save it into database:
private void productsDetailsApi() {
String tag_json_obj = "json_obj_req";
String url = Constants.PRODUCTS_DETAILS_URL;
pBar.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("product_response", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject company = jsonObject.getJSONObject("company");
ModelProductDetail modelProductDetail = new ModelProductDetail();
modelProductDetail.setCompany_id(jsonObject.getString("company_id"));
modelProductDetail.setProduct_name_nl(jsonObject.getString("name_nl"));
modelProductDetail.setProduct_name_fr(jsonObject.getString("name_fr"));
modelProductDetail.setProduct_desc(jsonObject.getString("description"));
modelProductDetail.setProduct_id(jsonObject.getString("id"));
modelProductDetail.setEan_code(jsonObject.getString("ean_code").trim());
modelProductDetail.setArticle_code(jsonObject.getString("article_code").trim());
modelProductDetail.setProduct_mbh(jsonObject.getString("mbh"));
modelProductDetail.setProduct_msrp(jsonObject.getString("msrp"));
modelProductDetail.setProduct_source(jsonObject.getString("source"));
modelProductDetail.setCompany_name(company.getString("name"));
modelProductDetail.setFranco_trading_value("");
modelProductDetail.setFranco_product_value(company.getString("franco_amount_product"));
dbHelper.addProductsDetails(modelProductDetail);
}
dbHelper.close();
ArrayList<ModelProductDetail> modelProductCodeList = dbHelper.getProductsArticleCode();
Log.e("TAG", "ModelProductDetail:art " + modelProductCodeList.size());
shopDetailsApi();
} catch (Exception e) {
e.printStackTrace();
}
//pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
// pBar.setVisibility(View.GONE);
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Databse Insert Query
//add products data
public void addProductsDetails(ModelProductDetail modelProductDetail) {
SQLiteDatabase productsDb = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PRODUCT_ID, modelProductDetail.getProduct_id());
values.put(KEY_PRODUCT_NAME_FR, modelProductDetail.getProduct_name_fr());
values.put(KEY_PRODUCT_NAME_NL, modelProductDetail.getProduct_name_nl());
values.put(KEY_PRODUCT_DESC, modelProductDetail.getProduct_desc());
values.put(KEY_PRODUCT_ART, modelProductDetail.getArticle_code());
values.put(KEY_PRODUCT_EAN, modelProductDetail.getEan_code());
values.put(KEY_PRODUCT_MBH, modelProductDetail.getProduct_mbh());
values.put(KEY_PRODUCT_MSRP, modelProductDetail.getProduct_msrp());
values.put(KEY_PRODUCT_SOURCE, modelProductDetail.getProduct_source());
values.put(KEY_COMPANY_ID, modelProductDetail.getCompany_id());
values.put(KEY_COMPANY_NAME, modelProductDetail.getCompany_name());
values.put(KEY_FRANCO_TRADING, modelProductDetail.getFranco_trading_value());
values.put(KEY_FRANCO_PRODUCT, modelProductDetail.getFranco_product_value());
productsDb.insert(TABLE_PRODUCT_DETAILS, null, values);
productsDb.close();
}
You could try wrapping all the inserts inside a transaction e.g. :-
JSONArray jsonArray = response.getJSONArray("data");
dbHelper.getWritableDatabase.beginTransaction(); //<<<<<<<<<< ADDED
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject company = jsonObject.getJSONObject("company");
ModelProductDetail modelProductDetail = new ModelProductDetail();
modelProductDetail.setCompany_id(jsonObject.getString("company_id"));
modelProductDetail.setProduct_name_nl(jsonObject.getString("name_nl"));
modelProductDetail.setProduct_name_fr(jsonObject.getString("name_fr"));
modelProductDetail.setProduct_desc(jsonObject.getString("description"));
modelProductDetail.setProduct_id(jsonObject.getString("id"));
modelProductDetail.setEan_code(jsonObject.getString("ean_code").trim());
modelProductDetail.setArticle_code(jsonObject.getString("article_code").trim());
modelProductDetail.setProduct_mbh(jsonObject.getString("mbh"));
modelProductDetail.setProduct_msrp(jsonObject.getString("msrp"));
modelProductDetail.setProduct_source(jsonObject.getString("source"));
modelProductDetail.setCompany_name(company.getString("name"));
modelProductDetail.setFranco_trading_value("");
modelProductDetail.setFranco_product_value(company.getString("franco_amount_product"));
dbHelper.addProductsDetails(modelProductDetail);
}
dbHelper.getWritableDatabase.setTransactionSuccessful(); //<<<<<<<<<< ADDED
dbHelper.getWritableDatabase.endTransaction(); //<<<<<<<<<< ADDED
dbHelper.close();
To use the above you would also have to remove the line
productsDb.close();
From the Insert Query
The carList is declared as a public variable in the class, and the log shows that values are added in the array, yet when I call the list is empty, how to solve it with Volley response?
public void onResponse(JSONObject response) {
try {
JSONArray resArray = response.getJSONArray("result");
for(int i=0;i<resArray.length();i++) {
JSONObject car = resArray.getJSONObject(i);
String id = car.getString("id");
String brand = car.getString("brand");
String created = car.getString("created");
carList.add(new CarListItem(brand, plate_number));
Log.d(TAG, "ADDED___: " +brand + " " + plate_number);
}
Thanks
#Benp
You right, the solution is to add the recycler adapter within the onResponse body as here:
public void onResponse(JSONObject response) {
try {
JSONArray resArray = response.getJSONArray("result");
for (int i = 0; i < resArray.length(); i++) {
JSONObject car = resArray.getJSONObject(i);
String id = car.getString("id");
String brand = car.getString("brand");
String created = car.getString("created");
carList.add(new CarListItem(car_id, brand, plateNumber, color));
}
} catch (JSONException e) {
e.printStackTrace();
}
if (carList.size() > 0) {
mAdapter = new RecyclerAdapterCarsList(carList);
buildRecyclerView();
}
}
It was simple, need a tiny clue to fix it ;)
Thanks for helping
I can parse json from an url in this way:
String link1 = "http://www.url.com/test1.json";
String link2 = "http://www.url.com/test2.json";
private void fetchMovies() {
String url = link1;
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
I want to parse my json from multiple url.
I want to parse url1 and url2 at the same time.
How can I do that?
Why don't you use "links" as array ?
In case you will use an array:
JSONObject jsonObject = new JSONObject();
JSONArray keys = jsonObject.getJSONArray("links");
int length = keys.length();
for (int i = 0; i < length; i++) {
new ReadJSON().execute(keys.getString(i));
}
Anyway, you take all the keys and go one after the other, and then query each
EDIT:
JSONObject jsonObject = new JSONObject(/*Your links json*/);
JSONObject links = jsonObject.get("links");
Iterator<String> keys = links.keys();
while (keys.hasNext()) {
new ReadJSON().execute(links.getString(keys.next()));
}
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() );
}
})
this is my request code ,please help me to parse it correctly. I want all the options for each particular question but I am getting only one option .can anyone solve it. I have attached SS of my data format.
JsonObjectRequest request = new JsonObjectRequest(
"http://www.proprofs.com/quiz-school/mobileData/request.php?request=QuizStart&module=handShake&title=does-your-crush-like-you-girls-only_1",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
// ArrayList<Data> listData = new ArrayList<>();
if (response != null && response.length() > 0) {
try {
JSONArray array = response.getJSONArray("quiz");
// JSONObject jsonObject = array.getJSONObject(0);
for (int i = 0; i < array.length(); i++) {
JSONObject currentArray = array.getJSONObject(i);
DataQuestions movie = new DataQuestions();
movie.setQuestion(currentArray.getString("question"));
String question = currentArray.getString("question");
System.out.println("question----------" + question);
movie.setQuesImage(currentArray.getString("QuesImage"));
String image = currentArray.getString("QuesImage");
System.out.println("QuesImage----------" + image);
JSONArray keys= currentArray.getJSONArray("keys");
for(int j =0;j<keys.length();j++){
JSONObject keyobject = keys.getJSONObject(j);
movie.setOption(keyobject.getString("option"));}
/*String key = null;
if(keys.getJSONObject("option")) {
key = keys.getString("option");
}
movie.setOption(key);*/
/* JSONArray jsonArray1 = (jsonObject.getJSONArray("keys"));
int numberOfItemsInResp = jsonArray1.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
DataQuestions options = new DataQuestions();
// movie = new DataQuestions();
options.setOption(jsonObject2.getString("option"));
String optios = jsonObject2.getString("option");
System.out.println("option----------" + options);
// JSONArray jsonArray1 = (response.getJSONArray("keys"));*/
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
Toast.makeText(MainActivity.this, "No Items Available", Toast.LENGTH_LONG).show();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request);
}
This is because, you use a single object in second for loop. You should to define keys object and stored within arraylist in main object. Like this
public class Quiz {
String quizId;
String QuesImage;
String question;
String questionId;
String Type;
int index;
ArrayList<Keys> keysList;
}
public class Keys{
String answerId;
String option;
String AnsImage;
}
and parse it
JSONArray array = response.getJSONArray("quiz");
for (int i = 0; i < array.length(); i++){
JSONObject jsonObj = array.getJSONObject(i);
Quiz quiz = new Quiz();
quiz.QuesImage = jsonObj.getString("QuesImage");
quiz.question = jsonObj.getString("question");
quiz.questionId = jsonObj.getString("questionId");
quiz.Type = jsonObj.getString("Type");
quiz.index = jsonObj.getInt("index");
JSONArray keys = jsonObj.getJSONArray("keys");
for (int j = 0; j < keys.length(); j++) {
JSONObject keysObj = keys.getJSONObject(j);
Keys keys = new Keys();
keys.answerId = keysObj.getString("answerId");
keys.option = keysObj.getString("option");
keys.AnsImage = keysObj.getString("AnsImage");
quiz.keysList.add(keys);
}
}