I'm trying to set recyclerview data from this type of json response but data is not setting into recylerview
Response:
{
"vehicles": [
{
"id": 1,
"vehicle_number": "gj03fn3235",
"driver_id": 4,
"vehicle_type": "3",
"admindata": {
"id": 7,
"email": "chirag.pwt2#gmail.com"
},
"userdata": {
"id": 4,
"email": "keval.pwt#gmail.com"
}
},
{
"id": 2,
"vehicle_number": "gj03fn3236",
"driver_id": 4,
"vehicle_type": "4",
"admindata": {
"id": 7,
"email": "keval.pwt#gmail.com"
},
"userdata": {
"id": 4,
"email": "keval.pwt#gmail.com"
}
}
]
}
I have created a pojo class of response But my data is not setting into recylerview api call successfully but response print in logcat i tried to set vehicle_number and email in recylerview
Here is my java code:
#Override
public void onSuccess(int
statusCode, Header[] headers, JSONObject
response) {
super.onSuccess(statusCode,
headers, response);
try {
Gson gson = new
GsonBuilder().create();
List<VehicleList> list =
gson.fromJson(response.getJSONArray
("vehicles").toString(), new
TypeToken<List<VehicleList>>() {
}.getType());
Log.e("listsize",""+list.size());
if (list.size() == 0) {
txt_error.setVisibility(View.VISIBLE);
} else {
VehiclesDriverAdpter
acceptedRequestAdapter = new
VehiclesDriverAdpter(list);
recyclerView.setAdapter
(acceptedRequestAdapter);
acceptedRequestAdapter.
notifyDataSetChanged();
}
} catch (JSONException e) {
}
}
My Adapter class:
public class VehiclesDriverAdpter extends
RecyclerView.Adapter<VehiclesDriverAdpter.Holder> {
List<VehicleList> list;
List<Vehicle> list1;
FragmentActivity activity;
public VehiclesDriverAdpter(List<VehicleList> list) {
this.list = list;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
return new
Holder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_vehicle, parent, false));
}
#Override
public void onBindViewHolder(final Holder holder, int position) {
final Vehicle pojo1 = list1.get(position);
Log.e("VehicleNumber",""+pojo1.getVehicleNumber());
holder.txt_vehicle_number.setText(pojo1.getVehicleNumber());
holder.txt_vehicle_driver_name.setText(pojo1.getUserdata().getEmail());
holder.drivername.setText(pojo.getDriver_name());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putSerializable("data", pojo1);
VehiclesInfoFragment detailFragment = new
VehiclesInfoFragment();
detailFragment.setArguments(bundle);
((HomeActivity) holder.itemView.getContext()).
changeFragment(detailFragment, "Passenger Information");
}
});
BookFont(holder, holder.txt_vehilce_type);
BookFont(holder, holder.txt_vehicle_driver_name);
BookFont(holder, holder.txt_vehicle_driver_mobile_no);
MediumFont(holder, holder.txt_vehicle_number);
}
#Override
public int getItemCount() {
return list.size();
}
public class Holder extends RecyclerView.ViewHolder {
TextView txt_vehicle_number, txt_vehilce_type, txt_vehicle_driver_name,
txt_vehicle_driver_mobile_no;
CircleImageView img_driver;
public Holder(View itemView) {
super(itemView);
txt_vehicle_number = (TextView)
itemView.findViewById(R.id.txt_vehicle_number);
txt_vehilce_type = (TextView)
itemView.findViewById(R.id.txt_vehilce_type);
txt_vehicle_driver_name = (TextView)
itemView.findViewById(R.id.txt_vehicle_driver_name);
txt_vehicle_driver_mobile_no = (TextView)
itemView.findViewById(R.id.txt_vehicle_driver_mobile_no);
}
}
public void BookFont(Holder holder, TextView view1) {
Typeface font1 =
Typeface.createFromAsset(holder.itemView.getContext().getAssets(),
"font/AvenirLTStd_Book.otf");
view1.setTypeface(font1);
}
public void MediumFont(Holder holder, TextView view) {
Typeface font =
Typeface.createFromAsset(holder.itemView.getContext().getAssets(),
"font/AvenirLTStd_Medium.otf");
view.setTypeface(font);
}
}
Try this one
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
setRecyclerData();
}
});
private void setRecyclerData(){
VehiclesDriverAdpter acceptedRequestAdapter = new VehiclesDriverAdpter(list);
recyclerView.setAdapter(acceptedRequestAdapter);
acceptedRequestAdapter.notifyDataSetChanged();
}
I think you have forgotten to add layout manager on your recyclerView add it in code like this
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getBaseContext());
recyclerView.setLayoutManager(mLayoutManager);
VehiclesDriverAdpter acceptedRequestAdapter = new VehiclesDriverAdpter(list);
recyclerView.setAdapter (acceptedRequestAdapter);
You put data to List<VehicleList> list list, but take it from List<Vehicle> list1;
You can try(but only if you always have one item in VehicleList) something like this
public VehiclesDriverAdpter(List<VehicleList> list) {
if(!list.isEmpty()){
this.list1 = list.get(0);
}
}
Related
I have an app that displays Cardviews in a recycler adapter. Each cardview gets its data from Firebase. My app shows classes a user can sign up for and I want the user to be able to click on the cardview, with the class they want, and save it under their UID.
Here is my code of the activity that shows English classes:
private FirebaseDatabase database;
private DatabaseReference myRef;
private List<Listdata> list;
private RecyclerView recyclerview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_english_classes);
recyclerview = (RecyclerView) findViewById(R.id.rview);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("English");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<>();
// String key = myRef.child("English").push().getKey();
// System.out.println(key);
// StringBuffer stringbuffer = new StringBuffer();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Class_model new_class = dataSnapshot1.getValue(Class_model.class);
String nameofclass = new_class.getDate_clasname();
String teacherofclass = new_class.getTeacher();
String roomnumberofclass = new_class.getRoom_number();
Listdata listdata = new Listdata(nameofclass, teacherofclass, roomnumberofclass);
//String name = userdetails.getName();
//String email = userdetails.getEmail();
//String address = userdetails.getAddress();
listdata.setDate_class(nameofclass);
listdata.setTeacher(teacherofclass);
listdata.setRnumber(roomnumberofclass);
list.add(listdata);
// Toast.makeText(MainActivity.this,""+name,Toast.LENGTH_LONG).show();
}
RecyclerviewAdapter recycler = new RecyclerviewAdapter(list);
RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(English_classes.this);
recyclerview.setLayoutManager(layoutmanager);
recyclerview.setItemAnimator(new DefaultItemAnimator());
recyclerview.setAdapter(recycler);
}
#Override
public void onCancelled(DatabaseError error) {
AlertDialog alertDialog = new AlertDialog.Builder(English_classes.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev#vigoschools.org!");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
// Failed to read value
// Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
//});
Here is the code for my Recycler Adapter:
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder>{
List<Listdata> listdata;
public RecyclerviewAdapter(List<Listdata> listdata) {
this.listdata = listdata;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_class_model,parent,false);
MyHolder myHolder = new MyHolder(view);
return myHolder;
}
public void onBindViewHolder(MyHolder holder, int position) {
Listdata data = listdata.get(position);
holder.vdate_class.setText(data.getDate_class());
holder.vteacher.setText(data.getTeacher());
holder.vrnumber.setText(data.getRnumber());
}
#Override
public int getItemCount() {
return listdata.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView vdate_class , vteacher,vrnumber;
public MyHolder(View itemView) {
super(itemView);
vdate_class = (TextView) itemView.findViewById(R.id.date_class_name);
vteacher = (TextView) itemView.findViewById(R.id.room_number);
vrnumber = (TextView) itemView.findViewById(R.id.teacher);
}
}
}
Here is my code for the Class model class:
public class Class_model {
String date_clasname;
String teacher;
String room_number;
public Class_model(){};
public Class_model(String date_cname, String teach, String room_n){
//subject = subject2;
date_clasname = date_cname;
teacher = teach;
room_number = room_n;
}
public String getDate_clasname() {
return date_clasname;
}
public void setDate_clasname(String date_clasname) {
this.date_clasname = date_clasname;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public String getRoom_number() {
return room_number;
}
public void setRoom_number(String room_number) {
this.room_number = room_number;
}
}
Here is my code for the List Data class:
public class Listdata {
public String date_class;
public String teacher;
public String rnumber;
public Listdata(String date_class, String teacher, String rnumber) {
this.date_class = date_class;
this.teacher = teacher;
this.rnumber = rnumber;
}
public String getDate_class() {
return date_class;
}
public void setDate_class(String date_class) {
this.date_class = date_class;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public String getRnumber() {
return rnumber;
}
public void setRnumber(String rnumber) {
this.rnumber = rnumber;
}
}
Here is my database structure:
{
"English" : {
"-Lgxm2KJPDbQG3C0flA2" : {
"date_clasname" : "english",
"room_number" : "d",
"teacher" : "f"
}
},
"Users" : {
"NnJlSVeqGXhJ2Nab2bhjr0HIpku2" : {
"Classes" : {
"-Lh1YFTY9L8XXZMMOHDb" : {
"date_clasname" : "ggh",
"room_number" : "hhh",
"teacher" : "uu"
},
"email" : "samuelford48#gmail.com",
"grade" : "12",
"name" : "Samuel Ford"
},
"cCEPKCKP99cnNZHxsktTBtOrG5Y2" : {
"Classes" : {
"-Lh1e_Rj9LBn6tkheIqO" : {
"date_clasname" : "gg",
"room_number" : "njgt",
"teacher" : "gg"
}
},
"email" : "matthewford48#gmail.com",
"grade" : "12",
"name" : "Matthew"
},
"zEEYIiWC3NXKa1adlChVtbxBML92" : {
"Classes" : {
"-Lh1b7UnsnNIA4BDDCv_" : {
"date_clasname" : "bb",
"room_number" : "bb",
"teacher" : "hb"
}
},
"email" : "svhsdev#vigoschools.org",
"grade" : "77",
"name" : "sa"
}
}
}
In essence, I want the user to be able to click on the english class displayed in the recycler adapter and add it to there list of classes which is under their uid. I don't have a problem with my code...I just don't know how to do it.
Put a click listener to your holder itemView, or the cardView in that itemView.
In you adapter.
public void onBindViewHolder(MyHolder holder, int position) {
Listdata data = listdata.get(position);
holder.vdate_class.setText(data.getDate_class());
holder.vteacher.setText(data.getTeacher());
holder.vrnumber.setText(data.getRnumber());
// #HERE
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
void onClick(View v) {
// Do your stuff here with your data
}
});
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to show this json in recyclerview. how can I do it?
I just want to list "user" and "exchangeName".
My Json;
{
"events": {
"101": {
"id": "0001",
"type": "exchange",
"user": "BTUser01",
"exchangeName": "BTCTurk",
"transactions": {
"send": "249",
"get": "24.1"
},
"certificate": [
"BTUser01Certificate"
]
},
"102": {
"id": "0002",
"type": "exchange",
"user": "BTUser02",
"exchangeName": "Koinim",
"transactions": {
"send": "300",
"get": "641"
},
"certificate": [
"BTUser02Certificate"
]
},
"103": {
"id": "0003",
"type": "exchange2",
"user": "BTUser03",
"exchangeName": "Koineks",
"transactions": {
"send": "823",
"get": "751"
},
"certificate": [
"BTUser03Certificate"
]
},
"104": {
"id": "0004",
"type": "exchange3",
"user": "BTUser04",
"exchangeName": "Paribu",
"transactions": {
"send": "543",
"get": "3.1"
},
"certificate": [
"BTUser04Certificate"
]
}
}
}
MainActivity;
public class MainActivity extends AppCompatActivity {
TextView ev, ev2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ev = (TextView) findViewById(R.id.ev);
ev2 = (TextView) findViewById(R.id.ev2);
Retrofit retrofit = new Retrofit.Builder().baseUrl("MYAPÄ°_ADRESS_LINK").addConverterFactory(GsonConverterFactory.create()).build();
Service service = retrofit.create(Service.class);
Call<ResponseBody> call = service.getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NonNull Call<ResponseBody> call, #NonNull Response<ResponseBody> response) {
if (response.isSuccessful()) {
String res = null;
if (response.body() != null) {
try {
res = response.body().string();
parse(res);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(#NonNull Call<ResponseBody> call, #NonNull Throwable t) {
int a = 0;
}
});
}
Model parse(String str) {
Model model = new Model();
try {
String source = str.replace("\n", "").replace("\t", "").replace("\r", "");
String s = new Gson().toJson(source);
s = s.replace("\\","");
s = s.substring(1,s.length()-1);
JSONObject object = new JSONObject(s).getJSONObject("events");
Iterator<String> iter = object.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = new JSONObject(String.valueOf(object.get(key)));
model.setExternalId(Integer.parseInt(key));
model.setUser(value.getString("user"));
model.setSend(value.getString("send"));
ev.setText(model.user);
ev2.setText(model.send);
return model;
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return model;
}
}
My Model;
public class Model {
int externalId;
int id;
String type;
String user;
String exchangeName;
Transactions transactions;
List<certificate> certificateList;
public int getExternalId() {
return externalId;
}
public void setExternalId(int externalId) {
this.externalId = externalId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getExchangeName() {
return exchangeName;
}
public void setExchangeName(String exchangeName) {
this.exchangeName = exchangeName;
}
public Transactions getTransactions() {
return transactions;
}
public void setTransactions(Transactions transactions) {
this.transactions = transactions;
}
public List<certificate> getCertificateList() {
return certificateList;
}
public void setCertificateList(List<certificate> certificateList) {
this.certificateList = certificateList;
}
class Transactions{
String send;
String get;
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send;
}
public String getGet() {
return get;
}
public void setGet(String get) {
this.get = get;
}
}
class certificate{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
First of all you could have found this answer easily in the hundreds of tutorials and guides available.
To achieve this you will need to create a custom adapter and a custom view for the adapter item.
To preface this answer. I wasn't sure if you want to show multiple Model items in the RecyclerView, or some other data. This example assumes that you use a List<Model>, however, it's an easy change to make it work with another list of objects.
Example of how the adapter could look like
public class MyAdapter extends RecyclerView.Adapter
{
private Context _context;
private List<Model> _items;
public void setItems(List<Model> items)
{
this._items = items;
notifyDataSetChanged();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
_context = parent.getContext();
return new MyAdapter.ItemViewHolder(parent);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position)
{
final MyAdapter.ItemViewHolder viewHolder = (MyAdapter.ItemViewHolder) holder;
final Model item = _items.get(position);
viewHolder._user.setText(item.user);
viewHolder._exchangeName.setText(item.exchangeName);
}
#Override
public int getItemCount()
{
return _items != null ? _items.size() : 0;
}
private static class ItemViewHolder extends RecyclerView.ViewHolder
{
private TextView _user;
private TextView _exchangeName;
private ItemViewHolder(ViewGroup parent)
{
super(LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_view, parent, false));
this._user = itemView.findViewById(R.id.user);
this._exchangeName = itemView.findViewById(R.id.exchange_name);
}
}
}
R.layout.adapter_view
This needs to be a view containing at least the two TextView views references from the MyAdapter above. Simple example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/content_container"
android:orientation="vertical"
android:animateLayoutChanges="true"
android:padding="#dimen/padding_view_large"
android:layout_marginBottom="#dimen/padding_view_small">
<TextView
android:id="#+id/user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/placeholder"
android:textColor="#color/black"
android:textSize="#dimen/text_size_medium"
android:layout_marginTop="#dimen/padding_view_small"/>
<TextView
android:id="#+id/exchange_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/placeholder"
android:textColor="#color/black"
android:textSize="#dimen/text_size_medium"
android:layout_marginTop="#dimen/padding_view_small"/>
</LinearLayout>
Binding the adapter
//First we set up the adapter and add our List<Model> object.
MyAdapter adapter = new MyAdapter();
adapter.setItems(... List<Model> items);
//Set up our RecyclerView and set the adapter.
final RecyclerView recyclerView = rootView.findViewById(R.id.model_list);
recyclerView.setLayoutManager(new LinearLayoutManager(_context));
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
You need to first understand (and later create) the following things
RecyclerView Adapter
RecyclerView ViewHolder
After you read up on those two things the solution will be pretty clear. Just to point you in the right direction, you will have to create a custom adapter which you will use to populate your custom viewholders. Hope this helps get you going. Feel free to ask if you need any more help in this.
Goal: keep track of selected items of a recyclerview using a changing Imageview for each row. Pratically i'm implementing a sort of checkbox.
Checking works fine:
but when I try to search for some items, checked items change: only first item of my list is checked:
I'll post my code below:
Shop Selected Interface
public interface NearestShopActivityAdapterListener {
void onShopSelected(FShop shop, View view);
}
My View Holder
public class MyHolder extends RecyclerView.ViewHolder{
public TextView name, address;
public ImageView logo;
public MyHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.activityNearestShopListItemUhop);
address = (TextView) itemView.findViewById(R.id.activityNearestShopListItemAddress);
logo = (ImageView) itemView.findViewById(R.id.activityNearestShopListItemImage);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onShopSelected(filteredShopList.get(getAdapterPosition()),view);
}
});
}
onShopSelected function
#Override
public void onShopSelected(FShop shop, View view) {
if(checkList.contains(shop.getShopId())){
mImgViewCheckBox = (ImageView) view.findViewById(R.id.checkBoxNearestShop);
mImgViewCheckBox.setImageResource(R.drawable.checkbox_selector_not_checked);
checkList.remove(shop.getShopId());
}else {
mImgViewCheckBox = (ImageView) view.findViewById(R.id.checkBoxNearestShop);
mImgViewCheckBox.setImageResource(R.drawable.ic_checked);
checkList.add(shop.getShopId());
}
}
Where I am wrong? I would try to associate the ImageView mImgViewCheckBox with the Shop id and not with its position in the recyclerview, but I have no idea on how to do it.
Thnak you in advance.
i have done this things in contact details. i provide my adapter and method you can change code your according needs .
InviteContactAdapter.java
public class InviteContactAdapter extends RecyclerView.Adapter<InviteContactAdapter.ItemViewHolder> implements Filterable {
private List<UserContact> mContactList = new ArrayList<>();
private List<UserContact> mContectFilter = new ArrayList<>();
private Context mContext;
private CustomFilter mFilter;
public List<String> mEmailList = new ArrayList<>();
public InviteContactAdapter(Context context, List<UserContact> mContactList) {
mContext = context;
this.mContactList = mContactList;
this.mContectFilter = mContactList;
mFilter = new CustomFilter();
}
public onItemClickListener onItemClickListener;
public void setOnItemClickListener(InviteContactAdapter.onItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.invite_contact_row_layout, viewGroup, false);
return new ItemViewHolder(view);
}
public interface onItemClickListener {
void onClick(UserContact contact);
}
#Override
public Filter getFilter() {
return mFilter;
}
#Override
public void onBindViewHolder(final ItemViewHolder itemViewHolder, int i) {
final UserContact contact = mContectFilter.get(i);
itemViewHolder.mTvUserNane.setText(contact.getUserName().trim());
itemViewHolder.mTvUserEmail.setText(contact.getUserEmail().trim());
if (contact.isSelect())
itemViewHolder.mIvSelect.setImageResource(R.drawable.check_contect);
else
itemViewHolder.mIvSelect.setImageResource(R.drawable.un_check_contact);
itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (contact.isSelect()) {
contact.setSelect(false);
itemViewHolder.mIvSelect.setImageResource(R.drawable.un_check_contact);
} else {
contact.setSelect(true);
itemViewHolder.mIvSelect.setImageResource(R.drawable.check_contect);
}
}
});
}
#Override
public int getItemCount() {
return mContectFilter.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView mTvUserNane, mTvUserEmail;
private ImageView mIvSelect;
public ItemViewHolder(View itemView) {
super(itemView);
mTvUserEmail = itemView.findViewById(R.id.icrlTvUserEmail);
mTvUserNane = itemView.findViewById(R.id.icrlTvUserName);
mIvSelect = itemView.findViewById(R.id.icrlIvSelect);
}
}
public List<String> getEmail() {
mEmailList.clear();
for (UserContact contact : mContectFilter) {
if (contact.isSelect()) {
mEmailList.add(contact.getUserEmail());
}
}
return mEmailList;
}
/**
* this class for filter data.
*/
class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results = new FilterResults();
if (charSequence != null && charSequence.length() > 0) {
ArrayList<UserContact> filters = new ArrayList<>();
charSequence = charSequence.toString().toUpperCase();
for (int i = 0; i < mContactList.size(); i++) {
if (mContactList.get(i).getUserName().toUpperCase().contains(charSequence) || mContactList.get(i).getUserEmail().toUpperCase().contains(charSequence)) {
UserContact contact = new UserContact();
contact.setUserName(mContactList.get(i).getUserName());
contact.setUserEmail(mContactList.get(i).getUserEmail());
filters.add(contact);
}
}
results.count = filters.size();
results.values = filters;
} else {
results.count = mContactList.size();
results.values = mContactList;
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mContectFilter = (ArrayList<UserContact>) filterResults.values;
notifyDataSetChanged();
}
}
}
then after bind contact data into recycler view and search data based on name and email..
make set adapter method ..
private void setAdapter(){
if (!mContactList.isEmpty()) {
inviteContactAdapter = new InviteContactAdapter(getActivity(), mContactList);
mRvData.setAdapter(inviteContactAdapter);
inviteContactAdapter.setOnItemClickListener(new InviteContactAdapter.onItemClickListener() {
#Override
public void onClick(UserContact contact) {
mEmailList.add(contact.getUserEmail());
}
});
} else {
mTvEmpty.setVisibility(View.VISIBLE);
}
}
then after make search data method ...
/**
* this method sort data.
*/
private void sortData(View root) {
mEtSearchData = (EditText) root.findViewById(R.id.icffEtSearch);
mEtSearchData.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (inviteContactAdapter != null) {
inviteContactAdapter.getFilter().filter(s);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
after getting contact data it will be work. and you can change code your according.
i have also some lets say template that I am using every time when I need recycler view.
The diffrence is that I am using one more additional property in every item of list, so basically you are not depending on filtering, sorting or something else.
This is XML for activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.arnela.nihad.expresssaladbar.RecyclerViewExample.RecyclerViewActivity">
<SearchView
android:id="#+id/searchViewBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:iconifiedByDefault="false"
android:queryHint="HINT"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:clipToPadding="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/searchViewBox" />
</android.support.constraint.ConstraintLayout>
Java class of RecyclerViewActivity is next one:
public class RecyclerViewActivity extends AppCompatActivity {
private RecyclerView mRecyclerList;
private RecyclerViewAdapter mRecyclerAdapter;
private List<DataVm> mSourceList = new ArrayList<>();
private SearchView txtSearchBox;
private Data data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyler_view);
data = new Data();
mSourceList.addAll(data.getSourceList(""));
// this is recycler view from xml
mRecyclerList = findViewById(R.id.recycler_view);
InitRecyclerView();
txtSearchBox = findViewById(R.id.searchViewBox);
txtSearchBox.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
mSourceList.clear();
mSourceList.addAll(data.getSourceList(s));
mRecyclerAdapter.notifyDataSetChanged();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
mSourceList.clear();
mSourceList.addAll(data.getSourceList(s));
mRecyclerAdapter.notifyDataSetChanged();
return false;
}
});
}
public void InitRecyclerView() {
mRecyclerList.setLayoutManager(new LinearLayoutManager(RecyclerViewActivity.this));
mRecyclerAdapter = new RecyclerViewAdapter(mSourceList, new IClickListenerAddRemove() {
#Override
public void onPositionClicked(int position, boolean isPicked) {
mSourceList.get(position).setPicked(isPicked);
}
});
mRecyclerList.setAdapter(mRecyclerAdapter);
}
}
Then, I have two helper class, one is for creating mockup data, with method for searching:
public class Data {
private List<DataVm> sourceList = null;
public Data() {
this.sourceList = new ArrayList<>();
// Items of the list and set all items to isPicked to false
sourceList.add(new DataVm(1, "Title 1", "Description 1", "", false));
sourceList.add(new DataVm(2, "Title 2", "Description 2", "", false));
sourceList.add(new DataVm(3, "Title 3", "Description 3", "", false));
sourceList.add(new DataVm(4, "Title 4", "Description 4", "", false));
sourceList.add(new DataVm(5, "Title 5", "Description 5", "", false));
sourceList.add(new DataVm(6 , "Title 6 ", "Description 6 ", "", false));
sourceList.add(new DataVm(7 , "Title 7 ", "Description 7 ", "", false));
sourceList.add(new DataVm(8 , "Title 8 ", "Description 8 ", "", false));
sourceList.add(new DataVm(9 , "Title 9 ", "Description 9 ", "", false));
sourceList.add(new DataVm(10, "Title 10", "Description 10", "", false));
sourceList.add(new DataVm(11, "Title 11", "Description 11", "", false));
sourceList.add(new DataVm(12, "Title 12", "Description 12", "", false));
}
public List<DataVm> getSourceList(String searchTitle) {
if (searchTitle.equals(""))
return sourceList;
List<DataVm> filteredList = new ArrayList<>();
for (DataVm item : sourceList) {
if (item.getTitle().contains(searchTitle)) {
filteredList.add(item);
}
}
return filteredList;
}
public void setSourceList(List<DataVm> sourceList) {
this.sourceList = sourceList;
}
}
And second helper class is basically class item for each row:
public class DataVm {
private int ItemId;
private String Title;
private String Description;
private String Image;
private boolean IsPicked;
public DataVm (int itemId, String title, String description, String image, boolean isPicked) {
ItemId = itemId;
Title = title;
Description = description;
Image = image;
IsPicked = isPicked;
}
public int getItemId() {
return ItemId;
}
public void setItemId(int itemId) {
ItemId = itemId;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public boolean isPicked() {
return IsPicked;
}
public void setPicked(boolean picked) {
IsPicked = picked;
}
}
Finally, two last classes are Adapter for list, and view holder for it.
Adapter class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<DataVm> mItemList;
private IClickListenerAddRemove listener;
public RecyclerViewAdapter(List<DataVm> itemList, IClickListenerAddRemove listener) {
mItemList = itemList;
this.listener = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.salad_creation_item_template, parent, false);
return new RecyclerViewHolder(view, listener);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
RecyclerViewHolder holder = (RecyclerViewHolder) viewHolder;
DataVm item = mItemList.get(position);
holder.setTitle(item.getTitle());
holder.setDescription(item.getDescription());
holder.setIsPicked(item.isPicked());
if (item.isPicked())
holder.setButtonDrawable(R.drawable.ic_remove_24dp);
else
holder.setButtonDrawable(R.drawable.ic_add_24dp);
}
#Override
public int getItemCount() {
return mItemList == null ? 0 : mItemList.size();
}
}
And the last one is view holder for list:
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView txtTitle;
private TextView txtDescription;
private ImageButton btnChecking;
private WeakReference<IClickListenerAddRemove> listenerRef;
private boolean mIsPicked = false;
public RecyclerViewHolder(View root, IClickListenerAddRemove listener) {
super(root);
listenerRef = new WeakReference<>(listener);
txtTitle = root.findViewById(R.id.txtTitle);
txtDescription = root.findViewById(R.id.txtDescription);
btnChecking = root.findViewById(R.id.btnAction);
btnChecking.setOnClickListener(this);
}
public void setIsPicked(boolean mIsPicked) {
this.mIsPicked = mIsPicked;
}
public void setTitle(CharSequence text) {
txtTitle.setText(text);
}
public void setDescription(CharSequence text) {
txtDescription.setText(text);
}
public void setButtonDrawable(int drawableId) {
btnChecking.setImageResource(drawableId);
}
#Override
public void onClick(View v) {
if (v.getId() == btnChecking.getId()) {
if (!mIsPicked) {
btnChecking.setImageResource(R.drawable.ic_remove_24dp);
mIsPicked = true;
}
else {
btnChecking.setImageResource(R.drawable.ic_add_24dp);
mIsPicked = false;
}
listenerRef.get().onPositionClicked(getAdapterPosition(), mIsPicked);
}
}
}
Structure of this looks like this:
Good day, I was watching an android tutorial.I followed it until it displayed the data successfully in the tutorial. but when I run my application it successfully parses the JSON response but it returns a null value when I try to display it.
This is my code
EstablishmentData.java
public class EstablishmentData implements Serializable {
public String estabName;
public String estabType;
public String estabAddress;
public String estabImage;
}
EstablishmentAdapter.java
public class EstablishmentAdapter extends RecyclerView.Adapter<EstablishmentAdapter.EstablishementViewHolder>{
private Context context;
private ArrayList<EstablishmentData> establishmentList;
public EstablishmentAdapter(Context context, ArrayList<EstablishmentData> establishmentList){
this.context= context;
this.establishmentList= establishmentList;
}
#Override
public EstablishementViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater= LayoutInflater.from(parent.getContext());
View view= inflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
EstablishementViewHolder estabHolder = new EstablishementViewHolder(view);
return estabHolder;
}
#Override
public void onBindViewHolder(EstablishementViewHolder holder, int position) {
EstablishmentData establishmentData= establishmentList.get(position);
String image_url= "http://10.0.3.2/blowOut/" + establishmentData.estabImage;
Picasso.with(context)
// .load(establishmentData.estabImage)
.load(image_url)
.placeholder(R.drawable.blowout)
.error(android.R.drawable.stat_notify_error)
.into(holder.estabImage);
holder.estabName.setText(establishmentData.estabName);
holder.estabName.setTextColor(Color.rgb(255,0,0));
holder.estabAddress.setText(establishmentData.estabAddress);
holder.estabAddress.setTextColor(Color.rgb(255,0,0));
Log.d("Estab Adapter","Establishment logo: " +image_url);
Log.d("Estab Adapter","Establishment name: " +establishmentData.estabName);
Log.d("Estab Adapter","Establishment address: " +establishmentData.estabAddress);
}
#Override
public int getItemCount() {
if(establishmentList != null){
return establishmentList.size();
}
return 0;
}
//This is the ViewHolder class
public static class EstablishementViewHolder extends RecyclerView.ViewHolder{
public CardView cvItem;
public ImageView estabImage;
public TextView estabName;
public TextView estabAddress;
public EstablishementViewHolder(View itemView) {
super(itemView);
cvItem = itemView.findViewById(R.id.cvItem);
estabImage = itemView.findViewById(R.id.estabImage);
estabName = itemView.findViewById(R.id.estabName);
estabAddress = itemView.findViewById(R.id.estabAddress);
}
}
}
EstablishmentFragment.java
public class EstablishmentFragment extends Fragment {
final String TAG= "EstablishmentFragment";
RecyclerView rvItem;
CardView cvItem;
public EstablishmentFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_establishment, container, false);
rvItem= rootView.findViewById(R.id.rv_recycler_view_fragment_accounts); //fragment_establishment.xml-> rvItem
rvItem.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rvItem.setLayoutManager(llm);
StringRequest stringRequest= new StringRequest(Request.Method.GET, AppConfig.URL_ESTABLISHMENT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
ArrayList<EstablishmentData> establishmentData = new JsonConverter<EstablishmentData>()
.toArrayList(response, EstablishmentData.class);
EstablishmentAdapter adapter= new EstablishmentAdapter(getContext(), establishmentData);
rvItem.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error != null){
Log.d(TAG, error.getMessage());
Toast.makeText(getActivity(), "Something went wrong", Toast.LENGTH_SHORT);
}
}
}
);
MySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
return rootView;
}
}
JsonConverter.class
public class JsonConverter<T> {
public JsonConverter() {
}
public ArrayList<T> toArrayList(String jsonString, Class<T> clazz) {
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("dd/MM/yy HH:mm:ss");
Gson gson = builder.create();
Type type = new JsonConverter.ListParameterizedType(clazz);
ArrayList<T> list = (ArrayList)gson.fromJson(jsonString, type);
return list;
}
public List<T> toList(String jsonString, Class<T> clazz) {
List<T> list = this.toArrayList(jsonString, clazz);
return list;
}
private static class ListParameterizedType implements ParameterizedType {
private Type type;
private ListParameterizedType(Type type) {
this.type = type;
}
public Type[] getActualTypeArguments() {
return new Type[]{this.type};
}
public Type getRawType() {
return ArrayList.class;
}
public Type getOwnerType() {
return null;
}
}
}
JSON
[{
"name": "Lechon-nan",
"type": "Lechon",
"address": "Lechon street",
"image": "jollibee.png"
}, {
"name": "Lechon",
"type": "Lechon",
"address": "Lechon",
"image": "mcdo.png"
}]
Logcat
Adapter: Establishment image: http://10.0.3.2/blowOut/null
Adapter: Establishment address: null
Adapter: Establishment name: null
Use same name for variable in your pojo class like same as in Json key
public class EstablishmentData implements Serializable {
public String name;
public String type;
public String address;
public String image;
}
Like this.
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.