use same recyclerview adapter with different layout - android

I've a recyclerview adapter with 3 textviews. I used a model class to set texts. Now I want to use the same adapter with different layout and in a different class which only have 1 textview. When I tried, I got NullPointerException (may be becuz the other 2 textviews are blank). Is there any way to use same adapter with different layout and in different class?
// second class - I used 1 textview
public class Customers extends AppCompatActivity{
private CShowProgress cShowProgress;
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String CUSTOMERS = "http://192.168.200.3/ubooktoday/android/showspacustomerlist";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customers);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cShowProgress = CShowProgress.getInstance();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showCustomers();
}
private void showCustomers() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(Customers.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, CUSTOMERS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cShowProgress.hideProgress();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getApplicationContext(), R.layout.item_row_customer, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "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");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
return linearLayoutManager;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
}
// first class - I used all 3 textviews
public class Walkin extends Fragment{
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String DASHBOARD = "My API";
#Nullable
#Override
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.walkin, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showDashboard();
}
private void showDashboard() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, DASHBOARD,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("walkinlist");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
model.setTime(obj.getString("serviceDuration"));
model.setServname(obj.getString("service"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getActivity(), R.layout.item_row_dashboard, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} 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");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
return linearLayoutManager;
}
}
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter<TimeLineViewHolder> {
private List<TimeLineModel> mFeedList;
int resource;
private Context mContext;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList) {
this.resource = resource;
this.mContext = mContext;
mFeedList = feedList;
}
#Override
public TimeLineViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}
#Override
public void onBindViewHolder(TimeLineViewHolder holder, int position) {
TimeLineModel timeLineModel = mFeedList.get(position);
holder.servicename.setText(timeLineModel.getServname());
holder.custname.setText(timeLineModel.getCustname());
holder.time.setText(timeLineModel.getTime());
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}
// ViewHolder class
public class TimeLineViewHolder extends RecyclerView.ViewHolder {
public TextView servicename, custname, time;
public TimeLineViewHolder(View itemView, int viewType) {
super(itemView);
servicename = (TextView) itemView.findViewById(R.id.tv_service);
custname = (TextView) itemView.findViewById(R.id.tv_cust);
time = (TextView) itemView.findViewById(R.id.tv_time);
}
}

You can use the getItemViewType().
Make your adapter(here TimeLineAdapter) extend RecyclerView.Adapter only.
You can change the Adapter's constructer to recieve ItemType and use it in the getItemViewType
Override the int getItemViewType (int position) method in your adapter.
In the onCreateViewHolder you can differentiate between which layout you want to inflate by using the viewType parameter.
In onBindViewHolder use instanceof to check which ViewHolder was created and call the related bind functions
A Sample Code-
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter{
.....
int type;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList,int layoutType) {
.....
.....
type=layoutType;
}
#Override
public int getItemViewType(int position) {
return type;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType==1){
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}else{
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder2(view, viewType);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof TimeLineViewHolder){
TimeLineModel timeLineModel = mFeedList.get(position);
((TimeLineViewHolder) holder).servicename.setText(timeLineModel.getServname());
......
}
else if(holder instanceof TimeLineViewHolder2){
....
....
}
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}

Related

how can update date from adapter to recyclerView?

when I send new data or update the info, how can to change my recycle view?
I have used a dapter.notifyDataSetChanged(); , but it's not working...
I tried more method, but it all cannot change my recycler view
in my code
recyclerView = view.findViewById(R.id.recyclerCoin);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
listCoinDiamondModel = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getActivity());
getData();
adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
recyclerView.setAdapter(adapter);
private void sendGift(String postUserID) {
final String postUserIDD = postUserID;
final String GiftAmount = this.GiftAmount.getText().toString().trim();
final String flag = "1";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_GIFTCOIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Log.d("FID", fid);
params.put("fid", fid);
params.put("GiftAmount", GiftAmount);
params.put("flag", flag);
params.put("postUserID", postUserIDD);
params.put("uid", getID);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private JsonArrayRequest getDataFromServer(int requestCount) {
//Initializing ProgressBar
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Load...");
progressDialog.dismiss();
final String GROUP_LIST = "https://example.com/aaa.php?flag=1&fid="+ getActivity().getIntent().getStringExtra("fid") +"&page="+requestCount;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(GROUP_LIST,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "No More gift Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
//This method will get data from the web api
private void getData() {
requestQueue.add(getDataFromServer(requestCount));
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the newFeedModel object
final CoinDiamondModel coinDiamondModel = new CoinDiamondModel();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
String TAG_Coin = "Coin";
String TAG_Diamond = "Diamond";
String TAG_UserName = "UserName";
String TAG_UserPhoto = "UserPhoto";
String TAG_UserID = "UserID";
//Log.d("NAME111", json.getString(json.getString(TAG_UserName)));
coinDiamondModel.setCoin(json.getString(TAG_Coin));
coinDiamondModel.setDiamond(json.getString(TAG_Diamond));
coinDiamondModel.setGiftFromUserName(json.getString(TAG_UserName));
coinDiamondModel.setGiftFromUserPhoto(json.getString(TAG_UserPhoto));
coinDiamondModel.setGiftFromUserID(json.getString(TAG_UserID));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the newFeedModel object to the list
listCoinDiamondModel.add(coinDiamondModel);
//adapter.addTheCoinData(coinDiamondModel);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
who knows what's happen and how can solve this?
could you told me how can I do, please?
adapter all code
public class CoinAdapter extends RecyclerView.Adapter<CoinAdapter.ViewHolder> {
private ImageLoader imageLoader;
private List<CoinDiamondModel> newcoinDiamondLists;
private RequestManager glide;
private Context context;
SessionManager sessionManager;
private String getID,memail;
public CoinAdapter(List<CoinDiamondModel> newcoinDiamondLists, Context context) {
this.newcoinDiamondLists = newcoinDiamondLists;
this.glide = Glide.with(context);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.coinlist, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
sessionManager = new SessionManager(getApplicationContext());
sessionManager.checkLogin();
HashMap<String, String> user = sessionManager.getUserDetail();
getID = user.get(sessionManager.USERID);
memail = user.get(sessionManager.EMAIL);
//String gid = getIntent.getStringExtra("xxx");
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
CoinDiamondModel newCoinDiamondModel = newcoinDiamondLists.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
holder.userName.setText(newCoinDiamondModel.getGiftFromUserName());
holder.userID.setText(newCoinDiamondModel.getGiftFromUserID());
holder.coinCount.setText(" x "+newCoinDiamondModel.getCoin());
glide.load(newCoinDiamondModel.getGiftFromUserPhoto()).into(holder.userPhoto);
}
#Override
public int getItemCount() {
return newcoinDiamondLists.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView userPhoto;
TextView userName,userID,coinCount;
ImageView coinImg;
public ViewHolder(#NonNull View itemView) {
super(itemView);
userPhoto = (CircleImageView) itemView.findViewById(R.id.userPhoto);
userName = (TextView) itemView.findViewById(R.id.userName);
coinCount = (TextView) itemView.findViewById(R.id.coinCount);
userID = (TextView) itemView.findViewById(R.id.userID);
coinImg = (ImageView) itemView.findViewById(R.id.coinImg);
}
}
public void addTheCoinData(CoinDiamondModel coinDiamondModel){
if(coinDiamondModel!=null){
newcoinDiamondLists.add(coinDiamondModel);
notifyDataSetChanged();
}else {
throw new IllegalArgumentException("無資料!");
}
}
}
you can again set the adapter to recycler view after the response of the server
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
adapter = new CoinAdapter(listCoinDiamondModel, getActivity());
recyclerView.setAdapter(adapter);
}
solution 2:
in your adapter write a function to update you list
and call function in activity
add this function to the adapter
public void updateList(List<CoinDiamondModel> list){
newcoinDiamondLists = list;
notifyDataSetChanged();
}
and call a function updateList of when you need an update recyclerview
The RecyclerView initialization and notifyDataSetChanged() is used properly. As your question is not clear enough about the Adapter implementation of the RecyclerView, I can give you several suggestions to check.
In RecyclerView.Adapter check if getItemCount() method is properly overriden with returning the list length (not 0) like below:
#Override
public int getItemCount() {
return listdata.length;
}
In RecyclerView.Adapter check if onCreateViewHolder method is properly overriden with proper xml layout like below:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem= layoutInflater.inflate(R.layout.coin_xml_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
In RecyclerView.Adapter check if RecyclerView.ViewHolder class is properly extended
and linked the UI elements from the xml with the adapter like below:
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView coinTextView;
public ViewHolder(View itemView) {
super(itemView);
this.coinTextView = (TextView) itemView.findViewById(R.id.coinTextView);
}
}
In RecyclerView.Adapter check if onBindViewHolder method is properly overridden and updated the list component UI properly like below:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MyListData myListData = listdata[position];
holder.cointTextView.setText(listdata[position].getCoin());
}
Debug with a breakpoint and check if the listCoinDiamondModel.add(coinDiamondModel) is calling or not and coinDiamondModel object is not empty.
The RecyclerView is placed properly in the activity xml, like the RecyclerView is Visible, has a decent size to show list elements. As an example:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
you can update your adapter list manually like this:(write this function in your adapter)
public void updateCoinAdapterList(ArrayList<listCoinDiamondModel> recyclerItemsList) {
this.recyclerItemsList = recyclerItemsList;
this.notifyDataSetChanged();
}
you must set your adapter global variable and initialize it in OnCreate or OnResume, and call
adapter.updateCoinAdapterList(listCoinDiamondModel);
when your list changed

Add dynamic data in recyclerview in another dynamic recyclerview

I am trying to add recyclerview to another recyclerview.
Like Sub Category Recyclerview in its Category RecyclerViews.
problem is that I am getting All categorie's sub category item list in last item of category list.
means
Cat1
cat2
catn(then below this list of subcat1, subcat2....so on)
but it should be like cat1 then in below subcat1 and so on...
here is MainActivity code from where I am calling the api and passing adapter to recyclerview
private void getCategory() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CategoryUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("DATA");
Log.v("Cat Response", response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
DataModel Model = new DataModel();
JSONObject jsonObject = jsonArray.getJSONObject(i);
catId = jsonObject.getString("ID");
catTitle = jsonObject.getString("TITLE");
Model.setTITLE(catTitle);
Model.setID(catId);
catList.add(Model);
categoryAdaptor.getSubCategory(catId);
}
categoryAdaptor.notifyDataSetChanged();
} catch (JSONException e) {
System.out.print("Exception is :" + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void setCatAdaptor() {
#SuppressLint("WrongConstant") LinearLayoutManager gridLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.VERTICAL, false);
recyclerView1.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
// call the constructor of CustomAdapter to send the reference and data to Adapter
categoryAdaptor = new CategoryAdaptor(this, catList);
recyclerView1.setAdapter(categoryAdaptor);
}
here is category adapter
public class CategoryAdaptor extends RecyclerView.Adapter<CategoryAdaptor.MyViewHlder> {
private Activity activity;
private ArrayList<DataModel> list;
private SubCategoryAdaptor subcategoryAdaptor;
private ArrayList<SubCatModel> subCatList = new ArrayList<>();
private String SubCategoryUrl = "http://philiabeauty.com/reader-choice/controller-api.php?action=get_subcategory_by_category&id=";
private String Token = "&access_token=Ym9va19kZXRhaWxz";
private String imgRoot = "http://philiabeauty.com/reader-choice/";
private String subCatId, subCatTitle, subCatImage;
public CategoryAdaptor(Activity activity, ArrayList<DataModel> list) {
this.activity = activity;
this.list = list;
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_list_layout, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
final DataModel model = list.get(i);
myViewHlder.catText.setText(model.getTITLE());
myViewHlder.catId.setText(model.getID());
setSubCatAdaptor(myViewHlder);
}
#Override
public int getItemCount() {
return list.size();
}
public void getSubCategory(String ID) {
String SubCategoryUrlFinal = SubCategoryUrl + ID + Token;
StringRequest stringRequest = new StringRequest(Request.Method.GET, SubCategoryUrlFinal, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("DATA");
Log.v("SubCat Response", response.toString());
for (int i = 0; i < 3; i++) {
SubCatModel Model = new SubCatModel();
JSONObject jsonObject = jsonArray.getJSONObject(i);
subCatId = jsonObject.getString("ID");
subCatTitle = jsonObject.getString("TITLE");
subCatImage = imgRoot + jsonObject.getString("IMG_SRC");
Model.setSubCatIMG(subCatImage);
Model.setSubCatTITLE(subCatTitle);
Model.setSubCatID(subCatId);
subCatList.add(Model);
}
subcategoryAdaptor.notifyDataSetChanged();
} catch (JSONException e) {
System.out.print("Exception is :" + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(activity);
requestQueue.add(stringRequest);
}
private void setSubCatAdaptor(MyViewHlder myView) {
Log.v("test", "test" );
#SuppressLint("WrongConstant") LinearLayoutManager gridLayoutManager = new LinearLayoutManager(activity, LinearLayout.HORIZONTAL, false);
myView.recyclerviewSubCat.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
// call the constructor of CustomAdapter to send the reference and data to Adapter
subcategoryAdaptor = new SubCategoryAdaptor(activity, subCatList);
myView.recyclerviewSubCat.setAdapter(subcategoryAdaptor);
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView catText, viewAllBtn, catId, tag;
private RecyclerView recyclerviewSubCat;
public MyViewHlder(#NonNull View itemView) {
super(itemView);
catText = itemView.findViewById(R.id.cat_name);
viewAllBtn = itemView.findViewById(R.id.viewAllBtn);
catId = itemView.findViewById(R.id.cat_id);
recyclerviewSubCat = itemView.findViewById(R.id.recyclerviewSubCat);
}
}
}
and here is the sub category adapter
public class SubCategoryAdaptor extends RecyclerView.Adapter<SubCategoryAdaptor.MyViewHlder> {
private Activity activity;
private ArrayList<SubCatModel> list;
public SubCategoryAdaptor(Activity activity, ArrayList<SubCatModel> list) {
this.activity = activity;
this.list = list;
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.subcat_list, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
final SubCatModel model = list.get(i);
Log.v("data", model.getSubCatTITLE());
myViewHlder.subCatTitle.setText(model.getSubCatTITLE());
myViewHlder.subCatId.setText(model.getSubCatID());
String img = model.getSubCatIMG();
Picasso.get()
.load(img)
.placeholder(R.drawable.ic_book_black_24dp)
.fit()
.into(myViewHlder.subCatImage);
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView subCatTitle, subCatId, subCatTag;
private ImageView subCatImage;
public MyViewHlder(#NonNull View itemView) {
super(itemView);
subCatTitle = itemView.findViewById(R.id.subcat_name);
subCatId = itemView.findViewById(R.id.subcat_id);
subCatTag = itemView.findViewById(R.id.subcat_tag);
subCatImage = itemView.findViewById(R.id.subcat_image);
}
}
}
Changed the sub category adapter declaration to viewHolder,
public class CategoryAdaptor extends RecyclerView.Adapter<CategoryAdaptor.MyViewHlder> {
private Activity activity;
private ArrayList<DataModel> list;
private String SubCategoryUrl = "http://philiabeauty.com/reader-choice/controller-api.php?action=get_subcategory_by_category&id=";
private String Token = "&access_token=Ym9va19kZXRhaWxz";
private String imgRoot = "http://philiabeauty.com/reader-choice/";
private String subCatId, subCatTitle, subCatImage;
public CategoryAdaptor(Activity activity, ArrayList<DataModel> list) {
this.activity = activity;
this.list = list;
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_list_layout, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
final DataModel model = list.get(i);
myViewHlder.catText.setText(model.getTITLE());
myViewHlder.catId.setText(model.getID());
getSubCategory(myViewHlder,model.getID());
}
#Override
public int getItemCount() {
return list.size();
}
public void getSubCategory(MyViewHlder myViewHlder,String ID) {
String SubCategoryUrlFinal = SubCategoryUrl + ID + Token;
StringRequest stringRequest = new StringRequest(Request.Method.GET, SubCategoryUrlFinal, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("DATA");
Log.v("SubCat Response", response.toString());
for (int i = 0; i < 3; i++) {
SubCatModel Model = new SubCatModel();
JSONObject jsonObject = jsonArray.getJSONObject(i);
subCatId = jsonObject.getString("ID");
subCatTitle = jsonObject.getString("TITLE");
subCatImage = imgRoot + jsonObject.getString("IMG_SRC");
Model.setSubCatIMG(subCatImage);
Model.setSubCatTITLE(subCatTitle);
Model.setSubCatID(subCatId);
myViewHlder.subCatList.add(Model);
}
myViewHlder.subcategoryAdaptor.notifyDataSetChanged();
} catch (JSONException e) {
System.out.print("Exception is :" + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(activity);
requestQueue.add(stringRequest);
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView catText, viewAllBtn, catId, tag;
private RecyclerView recyclerviewSubCat;
private SubCategoryAdaptor subcategoryAdaptor;
private ArrayList<SubCatModel> subCatList = new ArrayList<>();
public MyViewHlder(#NonNull View itemView) {
super(itemView);
catText = itemView.findViewById(R.id.cat_name);
viewAllBtn = itemView.findViewById(R.id.viewAllBtn);
catId = itemView.findViewById(R.id.cat_id);
recyclerviewSubCat = itemView.findViewById(R.id.recyclerviewSubCat);
LinearLayoutManager gridLayoutManager = new LinearLayoutManager(activity, LinearLayout.HORIZONTAL, false);
recyclerviewSubCat.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
// call the constructor of CustomAdapter to send the reference and data to Adapter
subcategoryAdaptor = new SubCategoryAdaptor(activity, subCatList);
recyclerviewSubCat.setAdapter(subcategoryAdaptor);
}
}
}

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) {
}}

Update database and refresh activity from another class when a card is clicked

I want that when anyone click on the CardView with Status=undone there should run an API and the database is updated and the refreshed data is loaded in RecyclerView.
This is my UpdateStatus.class having the RecyclerView data:
TextView Cid,Tno,Tname,Cono,Work;
private static final String
URL_GETDATA="";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_status);
Bundle bundle = getIntent().getExtras();
String cid = bundle.getString("checkID");
String tno = bundle.getString("trainno");
String tname = bundle.getString("trainname");
String cno = bundle.getString("coachno");
String works = bundle.getString("work");
Cid=(TextView)findViewById(R.id.idValue);
Cid.setText(cid);
Tno=(TextView)findViewById(R.id.tnoValue);
Tno.setText(tno);
Tname=(TextView)findViewById(R.id.tnameValue);
Tname.setText(tname);
Cono=(TextView)findViewById(R.id.cnoValue);
Cono.setText(cno);
Work=(TextView)findViewById(R.id.workValue);
Work.setText(works);
recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final AlertDialog dialog=new SpotsDialog(this, "Loading Data ...");
dialog.show();
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_GETDATA,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
Log.v("Response",response);
try {
JSONArray jsonArray=new JSONArray(response);
for (int i=0;i<jsonArray.length();i++){
ListItem item;
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.getString("status").equals("done")){
item=new ListItem(
jsonObject.getString("id"),
jsonObject.getString("checkID"),
jsonObject.getString("plannedDate"),
jsonObject.getString("actualDate"),
jsonObject.getString("status"),
R.drawable.done
);
}else {
item=new ListItem(
jsonObject.getString("id"),
jsonObject.getString("checkID"),
jsonObject.getString("plannedDate"),
jsonObject.getString("actualDate"),
jsonObject.getString("status"),
R.drawable.update
);
}
listItems.add(item);
}
adapter=new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
Bundle bundle = getIntent().getExtras();
// Posting params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("checkID",bundle.getString("checkID"));
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
This is my Adapter.class where the CardView data is loaded onClick on Card the Status is checked and An API will run using Volley and UpdateStatus activity must be refreshed with new data:
private List<ListItem> listItems;
private Context context;
private static final String
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final ListItem listItem=listItems.get(position);
holder.planned.setText(listItem.getPlanned());
holder.actual.setText(listItem.getActual());
holder.status.setImageResource(listItem.getmImageResourceid());
Intent i=new Intent(context,UpdateStatus.class);
holder.status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listItem.getStatus().equals("undone")){
//update code here
}
Toast.makeText(context,"You Clicked "+listItem.getStatus(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView planned,actual;
public ImageView status;
public LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
planned=(TextView)itemView.findViewById(R.id.planned_date);
actual=(TextView)itemView.findViewById(R.id.actual_date);
status=(ImageView)itemView.findViewById(R.id.status);
linearLayout=(LinearLayout)itemView.findViewById(R.id.linearLayout);
}
}
In OnResponse from volley when you adding a new data to your recyclerView just called a method recyclerView.notifyDataSetChanged() after recyclerView.setAdapter(adapter)
see the changes in you code below-:
#Override
public void onResponse(String response) {
dialog.dismiss();
Log.v("Response",response);
try {
JSONArray jsonArray=new JSONArray(response);
for (int i=0;i<jsonArray.length();i++){
ListItem item;
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.getString("status").equals("done")){
item=new ListItem(
jsonObject.getString("id"),
jsonObject.getString("checkID"),
jsonObject.getString("plannedDate"),
jsonObject.getString("actualDate"),
jsonObject.getString("status"),
R.drawable.done
);
}else {
item=new ListItem(
jsonObject.getString("id"),
jsonObject.getString("checkID"),
jsonObject.getString("plannedDate"),
jsonObject.getString("actualDate"),
jsonObject.getString("status"),
R.drawable.update
);
}
listItems.add(item);
}
adapter=new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);
recyclerView.notifyDataSetChanged()
} catch (JSONException e) {
e.printStackTrace();
}
}
},
Or for better user experience you can use recyclerView.notifyItemInserted(int position) instead of recyclerView.notifyDataSetChanged(). see documentation

How to sent JSON value from Fragment to module?

I have responsed JSONObject from API and i tried to send the response to the module using setter then to the Recyclerview adapter but its not working
This is my fragment
public class ListViewActivityFragment extends Fragment {
List<AppShowModule> appShowModule;
RecyclerView AppRecyclerView;
List<AppShowModule> GetDataAdapter1;
RecyclerView.LayoutManager AppRecyclerViewlayoutManager;
RecyclerView.Adapter AppRecyclerViewadapter;
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
TextView text;
Context context;
RequestQueue requestQueue;
public ListViewActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_view, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
appShowModule = new ArrayList<>();
AppRecyclerView = (RecyclerView) getView().findViewById( R.id.AppRecyclerView );
text = (TextView) getView().findViewById(R.id.textView2);
AppRecyclerView.setHasFixedSize( true );
GetDataAdapter1 = new ArrayList<>();
AppRecyclerView.setLayoutManager( AppRecyclerViewlayoutManager );
JsonAppShowData();}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json1 = jsonArray.getJSONObject( i ).getJSONObject("im:name");
AppShowModule appShowModule111 = new AppShowModule();
String name = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONObject("im:name").getString("label").toString();
text.setText(name);
appShowModule111.setAppName((name));}
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
AppRecyclerView.setLayoutManager(new LinearLayoutManager(context));
AppRecyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1,this);
AppRecyclerView.setAdapter(AppRecyclerViewadapter);
}
}
and this is my adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<AppShowModule> getDataAdapter;
Context MContext;
public RecyclerViewAdapter(List<AppShowModule> getDataAdapter, ListViewActivityFragment context){
super();
this.getDataAdapter = getDataAdapter;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.appitem, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
final AppShowModule getDataAdapter1 = getDataAdapter.get(position);
holder.NameTextView.setText(getDataAdapter1.getAppName());
Picasso.with(context).load(getDataAdapter1.getAppImageUrl()).into(holder.imgPost);
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView NameTextView;
public ImageView imgPost;
LinearLayout lnrLayout;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = (TextView) itemView.findViewById(R.id.appName);
imgPost = (ImageView) itemView.findViewById(R.id.appImage);
lnrLayout = (LinearLayout)itemView.findViewById(R.id.lnrLayout);
}
}
}
and this is my module
public class AppShowModule
{
private String appName;
private String appImageUrl;
public String getAppName() {
return appName;}
public void setAppName(String appName) {
this.appName = appName;}
public String getAppImageUrl() {
return appImageUrl;}
public void setAppImageUrl(String appImageUrl) {
this.appImageUrl = appImageUrl;}
}
Yo are creating the AppShowModule appShowModule111 = new AppShowModule(); Object but you never populated your adaapter with that object. Your JsonObjectRequest onResponse() should look like this;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json1 = jsonArray.getJSONObject( i ).getJSONObject("im:name");
AppShowModule appShowModule111 = new AppShowModule();
String name = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONObject("im:name").getString("label").toString();
text.setText(name);
appShowModule111.setAppName((name));
GetDataAdapter1.add(appShowModule111);
}
AppRecyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1,ListViewActivityFragment.this);
AppRecyclerView.setAdapter(AppRecyclerViewadapter);
} catch (JSONException e) {
e.printStackTrace();
}}

Categories

Resources