kani mozhi kani mozhi - 5 months ago 7
Android Question

How to update the Recylerview View items after displayed First Json URL In android

I having a problem update the Item in Recycler View.I will explain clearly about my problem.

I am using two Json URL's first Json URL can send the items to model class.
after completed this called the adapter, then update the second Json URL items with the adapter by using setter model class.

so that's why called adapter.notifyitemchanged, but only one time can updated items next time while looping doesn't update the items display empty for second time.

Code:

public void servicecallsingle(String list, final int pin) {
url = Constants.singleproducturl + list;


JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
@Override
public void onResponse(JSONObject response) {
JSONObject response1 = response;

if (response1 != null) {
// int status=jsonObject.optInt("status");
String status = response1.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
productpath = response1.getString("productPath");
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject responses = response1.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);

if (jsonarray.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < jsonarray.length(); i++) {
item = new CartItemoriginal();
JSONObject product = jsonarray.getJSONObject(i);
cartpid = product.getString("product_id");
cartproductname = product.getString("product_name");
cartaliasname = product.getString("product_alias");
cartprice = product.getString("mrp_price");
String sp = product.getString("selling_price");
String op = product.getString("offer_selling_price");
sellerid = product.getString("seller_id");
JSONArray pimg = product.getJSONArray("product_images");
JSONObject firstimg = pimg.getJSONObject(0);
cartimg = firstimg.getString("original_res");
String[] img2 = cartimg.split("\\.");
String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String Quantity = product.getString("product_max_add");
String minqty = product.getString("product_min_add");
int qty = Integer.parseInt(Quantity);

/*** calculation ***/
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
int ts1 = Integer.parseInt(ts);
String startdate1 = product.getString("offer_selling_start_date");
String endate1 = product.getString("offer_selling_end_date");

if (("".equals(startdate1)) && ("".equals(endate1))) {
// Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show();
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);

}
} else {

int startdate = Integer.parseInt(startdate1);
int endate2 = Integer.parseInt(endate1);

if (ts1 > startdate && ts1 < endate2) {
double offer = Double.parseDouble(op);
int offers = (int) offer;
price = String.valueOf(offers);
} else {
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
}
}

item.setProductname(cartproductname);
item.setQty(1);
item.setProductimg(imagone);
item.setMaxquantity(Quantity);
item.setAliasname(cartaliasname);
item.setPrice(price);
item.setMinquantity(minqty);
item.setProductid(cartpid);
cart.add(item);


// cart.add(new CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid));

}
}
} catch (JSONException e) {
e.printStackTrace();
}

} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}


// llm = new LinearLayoutManager(CartItems.this);

MainLinear.setVisibility(View.VISIBLE);
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
}

String id = cartpid;
String selleid = sellerid;
final int pinnum = pin;
String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum;
JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () {
@Override
public void onResponse(JSONObject responsesecond) {
JSONObject response2 = responsesecond;
// do something with response1 & response here...
if (response2 != null) {
// int status=jsonObject.optInt("status");
String status = response2.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
JSONObject responses = response2.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
Log.i(String.valueOf(jsonarray.length()), "message");
// looping through json and adding to movies list
for (int j = 0; j < jsonarray.length(); j++) {
JSONObject product = jsonarray.getJSONObject(j);
process = product.getString("process");
Message = product.getString("message");
if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) {
cartdelivery = product.getString("delivery");
cartshippingcharge = product.getString("shipping_charge");
String pincode = product.getString("pincode");

/**************************calculation of shipping days**************************/

int day = Integer.parseInt(cartdelivery);
Calendar c = Calendar.getInstance();
String dayNumberSuffix = getDayNumberSuffix(day);
SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy");

String currentDateandTime = sdf.format(new Date());

try {
c.setTime(sdf.parse(currentDateandTime));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, day);
Date resultdate = new Date(c.getTimeInMillis());
currentDateandTime = sdf.format(resultdate);
Log.d(String.valueOf(currentDateandTime), "shipping days");
cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime);
cart.get(j).setShippincharge(cartshippingcharge);
cart.get(j).setSellername("richard feloboune");

cartadapter.notifyItemChanged(j);
cartadapter.notifyItemRangeChanged(j, cart.size());

} else {
// cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum)));
cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum));
cartadapter.notifyItemChanged(j);
}
}
}

} catch (JSONException e) {
e.printStackTrace();
}
// stopping swipe refresh
// swipeRefreshLayout.setRefreshing(false);
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
}



pincheck();
}

}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request2);

}


}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request1);


}

Note: While looping first time can set the item in setter model class but second couldn't set the item to model class.

Anyone solve this problem glad to appreciate.

Thanks in advance

Answer

The problem is volley doesn't wait for the request to be completed. So as the first call is made within seconds other call will be also made. So, you need to create an interface which will be called when the first webservice is called, and than in interface call other webservice and than notifyDataSet.

     public void servicecallsingle(String list, final int pin) {
    url = Constants.singleproducturl + list;


  JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
 @Override
 public void onResponse(JSONObject response) {
     JSONObject response1 = response;

     if (response1 != null) {
         //   int status=jsonObject.optInt("status");
         String status = response1.optString("status");
         if (status.equalsIgnoreCase("200")) { //check the status 200 or not
             try {
                 productpath = response1.getString("productPath");
             } catch (JSONException e) {
                 e.printStackTrace();
             }
            parseJson(response1, new  WebServiceCallBack{
            public void getWebserviceCallBack(){
            // Call another webservice here
          String id = cartpid;
     String selleid = sellerid;
     final int pinnum = pin;
     String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum;
     JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () {
         @Override
         public void onResponse(JSONObject responsesecond) {
             JSONObject response2 = responsesecond;
             // do something with response1 & response here...
             if (response2 != null) {
                 //   int status=jsonObject.optInt("status");
                 String status = response2.optString("status");
                 if (status.equalsIgnoreCase("200")) { //check the status 200 or not
                     try {
                         JSONObject responses = response2.getJSONObject("response");
                         jsonarray = responses.getJSONArray(DATA);
                         if (jsonarray.length() > 0) {
                             Log.i(String.valueOf(jsonarray.length()), "message");
                             // looping through json and adding to movies list
                             for (int j = 0; j < jsonarray.length(); j++) {
                                 JSONObject product = jsonarray.getJSONObject(j);
                                 process = product.getString("process");
                                 Message = product.getString("message");
                                 if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) {
                                     cartdelivery = product.getString("delivery");
                                     cartshippingcharge = product.getString("shipping_charge");
                                     String pincode = product.getString("pincode");

                                     /**************************calculation of shipping days**************************/

                                     int day = Integer.parseInt(cartdelivery);
                                     Calendar c = Calendar.getInstance();
                                     String dayNumberSuffix = getDayNumberSuffix(day);
                                     SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy");

                                     String currentDateandTime = sdf.format(new Date());

                                     try {
                                         c.setTime(sdf.parse(currentDateandTime));
                                     } catch (ParseException e) {
                                         e.printStackTrace();
                                     }
                                     c.add(Calendar.DATE, day);
                                     Date resultdate = new Date(c.getTimeInMillis());
                                     currentDateandTime = sdf.format(resultdate);
                                     Log.d(String.valueOf(currentDateandTime), "shipping days");
                                     cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime);
                                     cart.get(j).setShippincharge(cartshippingcharge);
                                     cart.get(j).setSellername("richard feloboune");

                                     cartadapter.notifyItemChanged(j);
                                     cartadapter.notifyItemRangeChanged(j, cart.size());

                                 } else {
                                     // cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum)));
                                     cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum));
                                     cartadapter.notifyItemChanged(j);
                                 }
                             }
                         }

                     } catch (JSONException e) {
                         e.printStackTrace();
                     }
                     // stopping swipe refresh
                     // swipeRefreshLayout.setRefreshing(false);
                    } // condtion check the status 200
                 else // this is if status falied in runtime
                 {
                     Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
                 }
             }



             pincheck();
         }

     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
             Log.i("onErrorResponse", error.toString());
         }
     });
          AppController.getInstance().addToRequestQueue(request2);

 }


  }, new Response.ErrorListener() {
 @Override
 public void onErrorResponse(VolleyError error) {
     Log.i("onErrorResponse", error.toString());
 }
      });
             AppController.getInstance().addToRequestQueue(request1);

            });
             }

         } // condtion check the status 200
         else // this is if status falied in runtime
         {
             Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
         }


         // llm = new LinearLayoutManager(CartItems.this);

         MainLinear.setVisibility(View.VISIBLE);
         final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
         recyleitems.setHasFixedSize(false);
         recyleitems.setLayoutManager(layoutManager);
         cartadapter = new CartlistAdapter(cart, CartItems.this);
         Log.i(String.valueOf(cartadapter), "cartadapter");
         recyleitems.setAdapter(cartadapter);
         recyleitems.setNestedScrollingEnabled(false);
         myView.setVisibility(View.GONE);
         cartadapter.notifyDataSetChanged();
     }






      public void parseJson(JSONObject response1,  WebServiceCallBack       webserviceCallBack){
       try {
                 JSONObject responses = response1.getJSONObject("response");
                 jsonarray = responses.getJSONArray(DATA);

                 if (jsonarray.length() > 0) {
                     // looping through json and adding to movies list
                     for (int i = 0; i < jsonarray.length(); i++) {
                         item = new CartItemoriginal();
                         JSONObject product = jsonarray.getJSONObject(i);
                         cartpid = product.getString("product_id");
                         cartproductname = product.getString("product_name");
                         cartaliasname = product.getString("product_alias");
                         cartprice = product.getString("mrp_price");
                         String sp = product.getString("selling_price");
                         String op = product.getString("offer_selling_price");
                         sellerid = product.getString("seller_id");
                         JSONArray pimg = product.getJSONArray("product_images");
                         JSONObject firstimg = pimg.getJSONObject(0);
                         cartimg = firstimg.getString("original_res");
                         String[] img2 = cartimg.split("\\.");
                         String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
                         String Quantity = product.getString("product_max_add");
                         String minqty = product.getString("product_min_add");
                         int qty = Integer.parseInt(Quantity);

                         /***  calculation  ***/
                         Long tsLong = System.currentTimeMillis() / 1000;
                         String ts = tsLong.toString();
                         int ts1 = Integer.parseInt(ts);
                         String startdate1 = product.getString("offer_selling_start_date");
                         String endate1 = product.getString("offer_selling_end_date");

                         if (("".equals(startdate1)) && ("".equals(endate1))) {
                             // Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show();
                             if (cartprice.equalsIgnoreCase(sp)) {
                                 double d = Double.parseDouble(cartprice);
                                 int mrp = (int) d;
                                 price = String.valueOf(mrp);
                             } else {
                                 double s = Double.parseDouble(sp);
                                 int sales = (int) s;
                                 price = String.valueOf(sales);

                             }
                         } else {

                             int startdate = Integer.parseInt(startdate1);
                             int endate2 = Integer.parseInt(endate1);

                             if (ts1 > startdate && ts1 < endate2) {
                                 double offer = Double.parseDouble(op);
                                 int offers = (int) offer;
                                 price = String.valueOf(offers);
                             } else {
                                 if (cartprice.equalsIgnoreCase(sp)) {
                                     double d = Double.parseDouble(cartprice);
                                     int mrp = (int) d;
                                     price = String.valueOf(mrp);
                                 } else {
                                     double s = Double.parseDouble(sp);
                                     int sales = (int) s;
                                     price = String.valueOf(sales);
                                 }
                             }
                         }

                         item.setProductname(cartproductname);
                         item.setQty(1);
                         item.setProductimg(imagone);
                         item.setMaxquantity(Quantity);
                         item.setAliasname(cartaliasname);
                         item.setPrice(price);
                         item.setMinquantity(minqty);
                         item.setProductid(cartpid);
                         cart.add(item);


                         // cart.add(new       CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid));

                     }
                 }
             } catch (JSONException e) {
                 e.printStackTrace();}


                 webserviceCallBack.getWebserviceCallBack();

                 }



                 public interface WebServiceCallBack{
        public void getWebserviceCallBack()
     }
Comments