custom progress dialog not hiding - android

I'm trying to show custom progressbar using this 3rd party library in 2 fragments of TabLayout. I'm displaying the progressbar while in background I'm doing volley stringrequest. Problem is the progressbar is not hiding even after the result gets loaded from web service. This problem does not occurs when I use regular progressdialog with TabLayout. Although this custom progressbar works fine in normal layout, its not working in TabLayout. Is there any particular reason for this? Thanks.
// custom_progress_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#android:color/transparent"
android:orientation="vertical">
<com.wang.avi.AVLoadingIndicatorView
android:id="#+id/progress_bar"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:visibility="gone"
app:indicator="BallClipRotatePulse"
app:indicator_color="#android:color/darker_gray"/>
</RelativeLayout>
// One of the fragment of TabLayout
public class FirstFragment extends Fragment {
private TextView tv1;
private CShowProgress cShowProgress;
private static final String CUSTOMERS_INFO = "My API";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.first, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv1 = (TextView)view.findViewById(R.id.tv1);
cShowProgress = CShowProgress.getInstance();
showCustomersDetails();
}
private void showCustomersDetails() {
cShowProgress.showProgress(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, CUSTOMERS_INFO,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cShowProgress.hideProgress(); // THIS DOESNOT WORK AS PROGRESSBAR STILL SHOWS
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("aboutuser");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
String str1 = "Contact:" + obj.getString("primary_contact");
String str2 = "EMail:" + obj.getString("email");
String total = str1 + "\n" + str2;
tv1.setText(total);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
params.put("customer_id", "64");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
//Custom Class for 3rd party library of progressbar
public class CShowProgress {
public static CShowProgress s_m_oCShowProgress;
public static Context m_Context;
public Dialog m_Dialog;
public CShowProgress(Context m_Context) {
this.m_Context = m_Context;
}
public static CShowProgress getInstance() {
if (s_m_oCShowProgress == null) {
s_m_oCShowProgress = new CShowProgress(m_Context);
}
return s_m_oCShowProgress;
}
public void showProgress(Context m_Context) {
m_Dialog = new Dialog(m_Context);
m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
m_Dialog.setContentView(R.layout.custom_progress_layout);
m_Dialog.findViewById(R.id.progress_bar).setVisibility(View.VISIBLE);
m_Dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
m_Dialog.setCancelable(true);
m_Dialog.setCanceledOnTouchOutside(true);
m_Dialog.show();
}
public void hideProgress() {
if (m_Dialog != null) {
m_Dialog.dismiss();
m_Dialog = null;
}
}
}

try this,
public void hideProgress() {
if (m_Dialog != null) {
m_Dialog.setVisible(View.GONE);
m_Dialog = null;
}
}
OR in your onResponse()
cShowProgress.setVisible(View.GONE);

I made some changes in my custom progress dialog class and now it works...
public class CShowProgress extends Dialog{
private Dialog mpd = null;
private LayoutInflater inflater = null;
public CShowProgress(Context context) {
super(context)
}
public void showProgress(Context context) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.custom_progress_layout, null);
mpd = new Dialog(context);
mpd.requestWindowFeature(Window.FEATURE_NO_TITLE);
mpd.setContentView(view);
mpd.findViewById(R.id.progress_bar).setVisibility(View.VISIBLE);
mpd.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mpd.setCancelable(true);
mpd.show();
}
public void hideProgress() {
if (mpd != null) {
if (mpd.isShowing()){
mpd.dismiss();
}
}
}
}

Related

debugger showing -> 'this' is not available in onResponse method of volley for Recyclerview

I have this silly problem.
I searched for it but couldn't get any anwser hence I posted it here.
In following fragment I have recyclerview which populate data from server with Post POJO with help of Gson.
I have use similar code many times in my another projects, but today I got an error due to which my recyclerview is not showing values. So I debug code and I got following output which shows 'this' is not available for my recycleview inside onResponse of Volley.
My Fragment class is as follows:
public class Seller_Corner_Tab2 extends Fragment implements PostAdapter.OnItemClickListener {
public static final String TAG = Seller_Corner_Tab2.class.getSimpleName();
RecyclerView recyclerView;
ProgressDialog progressDialog;
AppPreferences preferences;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.seller_corner_tab2,container,false);
preferences = new AppPreferences(getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.seller_corner_2_rv);
LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(getContext()); // (Context context)
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
progressDialog = new ProgressDialog(getContext());
/*progressDialog.setMessage("Loading your Posts");
progressDialog.setCancelable(false);
progressDialog.show();*/
fetchSellerPosts();
return view;
}
public void fetchSellerPosts() {
final Seller seller = EKrushiKattaApplication.getInstance().getPrefManager().getSeller();
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.GETPOSTBYID, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Post>templist = new ArrayList<>();
/*progressDialog.hide();*/
try {
GsonBuilder gsonbuilder= new GsonBuilder();
Gson gson=gsonbuilder.create();
Log.e("Response",response);
templist =gson.fromJson(response, new TypeToken<List<Post>>(){}.getType());
}catch (Exception e)
{
e.printStackTrace();
}
recyclerView.setAdapter( new PostAdapter(templist,getContext(),Seller_Corner_Tab2.this));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Connection error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getActivity(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(CommonLib.SELLER_ID,String.valueOf(seller.getSellerId()));
Log.e(TAG, "params: " + params.toString());
return params;
}
};
//Adding request to request queue
EKrushiKattaApplication.getInstance().addToRequestQueue(strReq);
}
#Override
public void onItemClick(Post post) {
}}
My debugger showing me this output
My PostAdapter Class is as follows :
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder>{
private ArrayList<Post> posts;
private Context context;
private OnItemClickListener listener;
public PostAdapter(ArrayList<Post> posts, Context context, OnItemClickListener listener) {
this.posts = posts;
this.context = context;
this.listener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_post, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
if(posts!=null){
final Post post = posts.get(position);
holder.title.setText(post.getPostTitle());
holder.desc.setText(post.getPostDescription());
holder.cost.setText(post.getPostCost());
RequestOptions options = new RequestOptions()
.centerCrop()
// .placeholder(R.drawable.placeholder)
// .error(R.drawable.ic_pic_error)
.priority(Priority.HIGH);
new GlideImageLoader(holder.image,
holder.progressBar).load(EndPoints.BASE_URL+post.getPostImage(),options);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(post);
}
});
}
}
#Override
public int getItemCount() {
int size=0;
try {
size = posts.size();
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView title,desc,cost;
ProgressBar progressBar;
public ViewHolder(View itemView) {
super(itemView);
image=(ImageView)itemView.findViewById(R.id.post_item_image);
title=(TextView)itemView.findViewById(R.id.post_item_title);
desc=(TextView)itemView.findViewById(R.id.post_item_desc);
cost=(TextView)itemView.findViewById(R.id.post_item_cost);
progressBar=(ProgressBar)itemView.findViewById(R.id.post_item_progressbar);
}
}
public interface OnItemClickListener {
void onItemClick(Post post);
}}
Try this:
1) Pull the data source creation out of the onResponse()
2) Create adapter right after recycler view inflation.
3) In onResponse() fill data source with new data.
4) Call notifyDatasetChanged() in adapter.
public class Seller_Corner_Tab2 extends Fragment implements PostAdapter.OnItemClickListener {
public static final String TAG = Seller_Corner_Tab2.class.getSimpleName();
RecyclerView recyclerView;
ProgressDialog progressDialog;
AppPreferences preferences;
ArrayList<Post>templist = new ArrayList<>();
PostAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.seller_corner_tab2,container,false);
preferences = new AppPreferences(getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.seller_corner_2_rv);
LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(getContext()); // (Context context)
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
progressDialog = new ProgressDialog(getContext());
adapter = new PostAdapter(templist,getContext(),this);
recyclerView.setAdapter(adapter);
/*progressDialog.setMessage("Loading your Posts");
progressDialog.setCancelable(false);
progressDialog.show();*/
fetchSellerPosts();
return view;
}
public void fetchSellerPosts() {
final Seller seller = EKrushiKattaApplication.getInstance().getPrefManager().getSeller();
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.GETPOSTBYID, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Post> newList = new ArrayList();
/*progressDialog.hide();*/
try {
GsonBuilder gsonbuilder= new GsonBuilder();
Gson gson=gsonbuilder.create();
Log.e("Response",response);
templist =gson.fromJson(response, new TypeToken<List<Post>>(){}.getType());
}catch (Exception e)
{
e.printStackTrace();
}
templist.addAll(newList);
adapter.notifyDatasetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Connection error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getActivity(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(CommonLib.SELLER_ID,String.valueOf(seller.getSellerId()));
Log.e(TAG, "params: " + params.toString());
return params;
}
};
//Adding request to request queue
EKrushiKattaApplication.getInstance().addToRequestQueue(strReq);
}
#Override
public void onItemClick(Post post) {
}}

how to set on click listener on recyclerview and open a static page and get content from json url

i have a series of items in recyclerview .i want to set on click listener and open a description page of specific item and set data from json url. i have already made an adapter for description screen and a bean class. i dont know how to set adapter on layout. is it possible to set an adapter on linear layout to show static content from json url?
My code is :
Description activity
private class MakeRequestForGetDescription extends AsyncTask<String, Void, String> {
ProgressDialog Pdialog;
private String response;
private MakeServiceClass makeServiceClass = new MakeServiceClass();
#Override
protected void onPreExecute() {
Pdialog = new ProgressDialog(getActivity());
Pdialog.setMessage("Please Wait..");
Pdialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
HashMap<String, String> parms = new HashMap<String, String>();
response = makeServiceClass.makeServiceConnectionGet(ConstUrl.DESCRP_URLS);
Log.e("response ads", response);
} catch (Exception ex) {
ex.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(response);
if (Pdialog != null) {
Pdialog.dismiss();
}
if (response != null) {
try {
JSONObject mainObject = new JSONObject(response);
if (mainObject.has("status")) {
String Status = mainObject.getString("status");
String img_url = "";
if (Status.equalsIgnoreCase("200")) {
if (mainObject.has("img_url")) {
img_url = mainObject.getString("img_url");
Log.e("img_url", img_url);
}
if (mainObject.has("details")) {
JSONArray datArray = mainObject.getJSONArray("details");
descriptionBeanArrayList = new ArrayList<>();
if (datArray.length() > 0) {
for (int i = 0; i < datArray.length(); i++) {
DescriptionBean descriptionBean = new DescriptionBean();
JSONObject internalDataObject = datArray.getJSONObject(i);
if (internalDataObject.has("id")) {
descriptionBean.setId(internalDataObject.getString("id"));
}
if (internalDataObject.has("title_en")) {
descriptionBean.setTitle_en(internalDataObject.getString("title_en"));
}
if (internalDataObject.has("ad_description_en")) {
descriptionBean.setAd_description_en(internalDataObject.getString("ad_description_en"));
}
if (internalDataObject.has("price")) {
descriptionBean.setPrice(internalDataObject.getString("price"));
}
if (internalDataObject.has("km_driven")) {
descriptionBean.setKm_driven(internalDataObject.getString("km_driven"));
}
if (internalDataObject.has("image_file")) {
descriptionBean.setImage_file("http://" + img_url + internalDataObject.getString("image_file"));
}
descriptionBeanArrayList.add(descriptionBean);
}
setAdapterForDescription();
}
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void setAdapterForDescription() {
DescriptionAdapter adapter = new DescriptionAdapter(getActivity(), descriptionBeanArrayList);
}
}
Description Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.fragment_description, parent,false);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvRate = (TextView) convertView.findViewById(R.id.tvRate);
viewHolder.tvMiles = (TextView) convertView.findViewById(R.id.tvMiles);
viewHolder.et_description = (EditText) convertView.findViewById(R.id.et_description);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
//setdata
viewHolder.tvTitle.setText(descriptionBeanArrayList.get(position).getTitle_en());
viewHolder.tvRate.setText(descriptionBeanArrayList.get(position).getPrice());
viewHolder.tvMiles.setText(descriptionBeanArrayList.get(position).getKm_driven());
viewHolder.et_description.setText(descriptionBeanArrayList.get(position).getAd_description_en());
Log.e("s", descriptionBeanArrayList.get(position).getImage_file());
//Glide.with(mContext).load("www.apnikheti.com/upload/buysell/idea99A4.jpg").into(viewHolder.iv_picofproduct);
Picasso.with(mContext).load(descriptionBeanArrayList.get(position).getImage_file()).into(viewHolder.iv_picofproduct, new Callback() {
#Override
public void onSuccess() {
Log.e("s", "sucess");
}
#Override
public void onError() {
Log.e("s", "failed");
}
});
Picasso.with(mContext).setLoggingEnabled(true);
return convertView;
}
public class ViewHolder {
private TextView tvTitle,tvRate,tvMiles;
private EditText et_description;
public ImageView iv_picofproduct;
}
}
This is my code which is used to retrieve data from url (Json Data) and load it into a recyclerview using adapter and passing the same values to another activity.
MyActivity
public class Video_List extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//private GridLayoutManager layoutManager;
private List<Video_Details> videodetails;
public static final String VideoID = "v_id";
public static final String ID = "id";
public static final String Title = "title";
public static final String Thumb = "thumb";
public static final String url = "http://115.115.122.10/paul/api/videos.php?start=1&count=10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video__list);
getdata();
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
//layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
videodetails = new ArrayList<>();
}
private void getdata(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("count",response.toString());
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Log.d("infoz","777"+error.getMessage());
Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
try {
for (int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
Video_Details video = new Video_Details();
if (json.has(VideoID)) {
Log.d("has values", json.getString(VideoID));
}
video.setId(json.getString(ID));
video.setV_id(json.getString(VideoID));
video.setTitle(json.getString(Title));
video.setThumb(json.getString(VideoID));
videodetails.add(video);
if (json.has(VideoID))
{
Log.d("Video",VideoID);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//Finally initializing our adapter
adapter = new DataAdapter(videodetails, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
MyAdapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<Video_Details> video;
public DataAdapter(List<Video_Details> video, Context context) {
super();
this.context = context;
this.video = video;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Video_Details videoDetails = video.get(position);
String url;
final String VideoID;
holder.title.setText(video.get(position).getTitle());
VideoID= video.get(position).getV_id();
url = video.get(position).getThumb();
Glide.with(context)
.load(url)
.override(150,70)
.into(holder.thumb);
//viewHolder.thumb.setText(android.get(i).getVer());
// viewHolder.tv_api_level.setText(android.get(i).getApi());
holder.vm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),Play_Video.class);
intent.putExtra("VideoId",(video.get(position).getV_id()));
intent.putExtra("Title",(video.get(position).getTitle()));
v.getContext().startActivity(intent);
}
}
);
}
#Override
public int getItemCount() {
return video.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView thumb;
public String videoid;
public View vm;
public ViewHolder(View view) {
super(view);
vm = view;
title = (TextView)view.findViewById(R.id.title);
thumb = (ImageView) view.findViewById(R.id.thumb);
//tv_version = (TextView)view.findViewById(R.id.tv_version);
//tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
}

Accessing volley response with callback interfaces

I m trying to extract android volley response to a member variable of the same class. I used callback interfaces to perform this task :
public void getData(MyCustomListener customListener) {
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, url,
response -> {
Log.i("response",response.toString());
customListener.onResponse(completeCart);
},
error -> Log.i("Volley_error", error.getMessage())) {
...
CustomerListener interface:
public interface MyCustomListener {
public void onResponse(Object response);
public void onError(String error_response);
}
And inside onCreateView method of the fragment :
getData(new MyCustomListener() {
#Override
public void onResponse(Object response) {
completeCartProItems.addAll((List<CompleteCartProItem>) response);
}
#Override
public void onError(String error_response) {}
});
When I put a debug pointer at completeCartProItems.addAll((List<CompleteCartProItem>) response); response is not empty but completeCartProItems arraylist is shown as empty.
Variables :
I need to pass this completeCartProItems to a Adapter named CartItem_ScrollerAdapter which has implemented to a RecycleView.
This implementation also inside the onCreateView of the fragment. right after calling getData() method :
cart_item_scrollerAdapter = new CartItem_ScrollerAdapter(getActivity(), completeCartProItems);
I put debug pointer inside the constructor of the CartItem_ScrollerAdapter as well.
But it also shows that the List parameter of the constructor is empty.
How to pass not empty ArrayList to the adapter given below ?? Any suggestions will be appreciable. Thank you.
UPDATE
Adapter class :
public class CartItem_ScrollerAdapter extends RecyclerView.Adapter<CartItem_ScrollerAdapter.CartItemViewHolder> {
private LayoutInflater inflater;
private List<CompleteCartProItem> completeCartProItems = new ArrayList<>();
private Context context;
public CartItem_ScrollerAdapter(Context context, List<CompleteCartProItem> completeCartProItems) {
this.inflater = LayoutInflater.from(context);
this.context = context;
this.completeCartProItems = completeCartProItems;
}
#Override
public CartItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.cart_item, parent, false);
CartItemViewHolder cartItemViewHolder = new CartItemViewHolder(view);
return cartItemViewHolder;
}
#Override
public void onBindViewHolder(CartItemViewHolder holder, int position) {
CompleteCartProItem proItem = completeCartProItems.get(position);
CartDetails details = (CartDetails) MyApplication.getAndroidSession().getAttribute("cart");
holder.cart_pro_name.setText(proItem.getP_name());
holder.cart_pro_price.setText("Rs " + (proItem.getP_dscPer() != 0 ? details.getDiscountPrice(proItem.getP_price(), proItem.getP_dscPer()) : proItem.getP_price()));
holder.cart_pro_qnty.setText(details.getQntyOfProduct(proItem.getPid(), proItem.getP_size()) + "");
holder.cart_pro_size.setText(proItem.getP_size());
String image_url = "http://10.0.2.2:8080/ECommerceApp/" + proItem.getP_img();
Picasso.with(context).load(image_url).into(holder.cart_pro_img);
}
#Override
public int getItemCount() {
return completeCartProItems != null ? completeCartProItems.size() : 0;
}
class CartItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView cart_pro_name;
TextView cart_pro_price;
TextView cart_pro_qnty;
TextView cart_pro_size;
ImageView cart_pro_img;
ImageButton cart_remove_btn;
Button cart_change;
public CartItemViewHolder(View itemView) {
super(itemView);
cart_pro_name = (TextView) itemView.findViewById(R.id.cart_item_product_name);
cart_pro_price = (TextView) itemView.findViewById(R.id.cart_item_product_price);
cart_pro_size = (TextView) itemView.findViewById(R.id.cart_item_size);
cart_pro_img = (ImageView) itemView.findViewById(R.id.cart_product_img);
cart_pro_qnty = (TextView) itemView.findViewById(R.id.cart_item_qnty);
//===============================================================================================
cart_remove_btn = (ImageButton) itemView.findViewById(R.id.remove_item_btn);
cart_change = (Button) itemView.findViewById(R.id.cart_item_change_btn);
cart_pro_img.setOnClickListener(this);
cart_remove_btn.setOnClickListener(this);
cart_change.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
}
Fragment :
public class CartFragment extends Fragment {
private RecyclerView cart_horizontal_scroller;
private CartItem_ScrollerAdapter cart_item_scrollerAdapter;
private Button purchase_button;
private List<CompleteCartProItem> completeCartProItems = new ArrayList<>();
public CartFragment() {
// Required empty public constructor
}
public void getData(MyCustomListener<CompleteCartProItem> customListener) {
if (MyApplication.getAndroidSession().getAttribute("cart") != null) {
Log.i("cart_null", "NOT null");
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
CartDetails cartDetails = (CartDetails) MyApplication.getAndroidSession().getAttribute("cart");
CopyOnWriteArrayList<CartItem> jsonSendArray = cartDetails.getShoppingList();
final String jsonString = new Gson().toJson(jsonSendArray,
new TypeToken<CopyOnWriteArrayList<CartItem>>() {
}.getType());
Log.i("json_object", jsonString);
String url = "http://10.0.2.2:8080/ECommerceApp/getAllProductsAction";
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, url,
response -> {
List<CompleteCartProItem> completeCart = new Gson().fromJson(response.toString(),
new TypeToken<List<CompleteCartProItem>>() {
}.getType());
Log.i("response", completeCart.get(0).getP_name());
customListener.onResponse(completeCart);
}, error -> Log.i("Volley_error", error.getMessage())) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("cartList", jsonString);
return params;
}
};
arrayRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 5000;
}
#Override
public int getCurrentRetryCount() {
return 5000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
requestQueue.add(arrayRequest);
} else {
Log.i("cart_null", "null");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cart, container, false);
cart_horizontal_scroller = (RecyclerView) view.findViewById(R.id.horizontal_scrollView_cart_items);
getData(new MyCustomListener<CompleteCartProItem>() {
#Override
public void onResponse(List<CompleteCartProItem> response) {
completeCartProItems.addAll(response);
//completeCartProItems.add(new CompleteCartProItem(1, 2340.0, "Extra Orient Top", "Orient", "", "S", 5));
Log.i("check", completeCartProItems.get(0).getP_name());
}
#Override
public void onError(String error_response) {
}
});
cart_item_scrollerAdapter = new CartItem_ScrollerAdapter(getActivity(), completeCartProItems);
cart_horizontal_scroller.setAdapter(cart_item_scrollerAdapter);
cart_horizontal_scroller.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
purchase_button = (Button) view.findViewById(R.id.purchase_btn);
purchase_button.setOnClickListener(v -> {
Toast t = Toast.makeText(getActivity(), "Worked", Toast.LENGTH_LONG);
t.show();
});
return view;
}
}
Ok. In reference to the comment above, I am writing some steps you should try since I do not have a clear picture of what might be wrong.
Let's start with your MyCustomListener. I do not know why are you setting the response type to Object. If it is to use this in multiple requests then you can modify it like the following with generics
public interface MyCustomListener<T> {
public void onResponse(T response);
public void onError(String error_response);
}
then use it like this when a callback is needed
getData(new MyCustomListener<List<CompleteCartProItem>>() {
#Override
public void onResponse(List<CompleteCartProItem> response) {
completeCartProItems.addAll(response);
}
#Override
public void onError(String error_response) {
//handle error
}
});
Also make sure you are not re-initialising completeCartProItems elsewhere after the callback.
Not really sure if the following will fix your issue but make sure that your callback is executed in the UI thread, too.

RecyclerView during OnRefresh adds another recyclerView List?

when I conduct onRefresh, my recyclerView adds on another copy to my current recyclerView instead of refreshing it, by looking at my code below does anyone know what the problem is?I have tried everything but nothing seems to work?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
//send our volley JSON Request
//Initialize VolleySingleton
mVolleySingleton = VolleySingleton.getInstance();
//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();
//2 types of requests an Array request and an Object Request
JSONArrayRequest();
}
private void JSONArrayRequest() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs=parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ToastTest.t(getActivity(), error.toString());
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String courseId = currentQuestions.getString("courseId");
String studentId = currentQuestions.getString("studentId");
data.append(text + "\n" + points + "\n" + courseId + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
listblogs.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_dashboard,container,false);
mRecyclerView=(RecyclerView)view.findViewById(R.id.fragment_dashboard);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapterDashBoard=new AdapterDashBoard(getActivity());
mRecyclerView.setAdapter(mAdapterDashBoard);
mPullToRefreshView = (PullToRefreshView)view.findViewById(R.id.pull_to_refresh);
mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
#Override
public void onRefresh() {
mPullToRefreshView.postDelayed(new Runnable() {
#Override
public void run() {
mPullToRefreshView.setRefreshing(false);
JSONArrayRequest();
}
}, REFRESH_DELAY);
}
});
return view;
}
}
public class AdapterDashBoard extends RecyclerView.Adapter<AdapterDashBoard.ViewDashboard>{
private LayoutInflater mLayoutInflater;
private ArrayList<Blogs> listblogs=new ArrayList<>();
public AdapterDashBoard(Context context){
mLayoutInflater=LayoutInflater.from(context);
}
public void setBloglist(ArrayList<Blogs> listBlogs){
this.listblogs=listBlogs;
notifyItemRangeChanged(0,listBlogs.size());
}
#Override
public ViewDashboard onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mLayoutInflater.inflate(R.layout.customizejson,parent,false);
ViewDashboard viewholder=new ViewDashboard(view);
return viewholder;
}
#Override
public void onBindViewHolder(ViewDashboard holder, int position) {
Blogs currentBlog=listblogs.get(position);
holder.questionText.setText(currentBlog.getMtext().toString());
holder.points.setText(currentBlog.getPoints().toString());
holder.id.setText(currentBlog.getId().toString());
}
#Override
public int getItemCount() {
return listblogs.size();
}
static class ViewDashboard extends RecyclerView.ViewHolder{
private ImageView thumbnail;
private TextView questionText;
private TextView points;
private TextView id;
public ViewDashboard (View itemView){
super(itemView);
//thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
questionText=(TextView)itemView.findViewById(R.id.questionText);
points=(TextView)itemView.findViewById(R.id.points);
id=(TextView)itemView.findViewById(R.id.ID);
}
}
}
You need to clear your listblogs list before adding new items. This is why you get duplicated values.
Also you're already adding new items to listblogs in parseJSONResponse() method, so there is no need for listblogs=parseJSONResponse(response); in onResponse() method, while its the same list.
Change your onResponse() method to:
#Override
public void onResponse(JSONArray response) {
listblogs.clear(); // here you clear the old data
parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}

hi.I tried to implement recycler view in side my fragment but unfortunately the app crashed

this is my fragment class
public class Frangment_electronics extends Fragment {
private static final String TAG = "RecyclerViewExample";
private RecyclerView mRecyclerView;
private RecyclerAdapter adapter;
private List<Listdetails> listdetails=new ArrayList<Listdetails>();
private static final String Url = "http://onam.leah.in/new/item_details.php";
private ProgressDialog progressDialog;
public Frangment_electronics(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_electronics, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
adapter = new RecyclerAdapter(getActivity(), listdetails);
mRecyclerView.setAdapter(adapter);
RequestQueue queue = Volley.newRequestQueue(getActivity());
showPD();
JsonArrayRequest movieReq1 = new JsonArrayRequest(Url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePD();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Listdetails item = new Listdetails();
item.setPhone_name(obj.getString("Phone"));
item.setPrice(obj.getString("Price"));
item.setThumbnail(obj.getString("Image"));
listdetails.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePD();
}
});
queue.add(movieReq1);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void showPD() {
if(progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog .setMessage("Loading...");
progressDialog .setCancelable(false);
progressDialog .setCanceledOnTouchOutside(false);
progressDialog .show();
}
}
private void hidePD() {
if (progressDialog != null) {
progressDialog .dismiss();
progressDialog = null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePD();
}
}
I am getting the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference at
info.androidhive.Groupdeal.app.MySingleton.getRequestQueue(MySingleton.java:61) at info.androidhive.Groupdeal.app.MySingleton.<init>(MySingleton.java:26)
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
RequestQueue queue = Volley.newRequestQueue(getActivity());
Replace getActivity() with rootView.getContext() in the lines above. There are many other places where you have used getActivity(). Replace them all with rootView.getContext(). In a fragment you cannot call the activity directly, instead you have to use whatever context is associated with the view created by the layout inflater.
EDIT : Change your showPD() code to this
private void showPD(Context context) {
if(progressDialog == null) {
progressDialog = new ProgressDialog(context);
progressDialog .setMessage("Loading...");
progressDialog .setCancelable(false);
progressDialog .setCanceledOnTouchOutside(false);
progressDialog .show();
}
}
and call it like this
Context context = rootView.getContext;
showPD(context);

Categories

Resources