Android studio select search results - java

I have simple problem with my Android app in Android Studio. I was to create two classes to add search activity in my app and was so successful. But, I have problem. The problem is that the user wants to select the person from the results and pass the user ID to another activity "User_Profile". But, I can't do this. Can anyone help me?
Search Class:
public class Search extends AppCompatActivity {
EditText se_input;
RecyclerView results_list;
DatabaseReference mUDB;
FirebaseUser mFBU;
SearchAdapter searchAdapter;
ArrayList<String> fullNameList,userNameList, userIdList,profileImageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mUDB = FirebaseDatabase.getInstance().getReference();
mFBU = FirebaseAuth.getInstance().getCurrentUser();
se_input = (EditText) findViewById(R.id.se_input);
results_list = (RecyclerView) findViewById(R.id.results_list);
results_list.setHasFixedSize(true);
results_list.setLayoutManager(new LinearLayoutManager(this));
results_list.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
/*
* Create a array list for each node you want to use
*/
fullNameList = new ArrayList<>();
userNameList = new ArrayList<>();
userIdList = new ArrayList<>();
profileImageList = new ArrayList<>();
se_input.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) {
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().isEmpty()) {
setAdapter(s.toString());
} else {
/*
* Clear the list when editText is empty
*/
fullNameList.clear();
userNameList.clear();
userIdList.clear();
profileImageList.clear();
results_list.removeAllViews();
}
}
});
}
private void setAdapter(final String searchedString) {
mUDB.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
/*
* Clear the list for every new search
*/
fullNameList.clear();
userNameList.clear();
userIdList.clear();
profileImageList.clear();
results_list.removeAllViews();
int counter = 0;
/*
* Search all users for matching searched string
*/
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String uid = snapshot.getKey();
String full_name = snapshot.child("name").getValue(String.class);
String user_name = snapshot.child("username").getValue(String.class);
String profile_pic = snapshot.child("image").getValue(String.class);
if (full_name.toLowerCase().contains(searchedString.toLowerCase())) {
fullNameList.add(full_name);
userNameList.add(user_name);
userIdList.add(uid);
profileImageList.add(profile_pic);
counter++;
} else if (user_name.toLowerCase().contains(searchedString.toLowerCase())) {
fullNameList.add(full_name);
userNameList.add(user_name);
userIdList.add(uid);
profileImageList.add(profile_pic);
counter++;
}
/*
* Get maximum of 15 searched results only
*/
if (counter == 15)
break;
}
searchAdapter = new SearchAdapter(Search.this, fullNameList, userNameList, userIdList, profileImageList);
results_list.setAdapter(searchAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
SearchAdapter Class:
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
Context context;
ArrayList<String> fullNameList,userNameList, userIdList,profileImageList;
class SearchViewHolder extends RecyclerView.ViewHolder
{
ImageView profileImage;
TextView full_name, user_name,user_id;
public SearchViewHolder(View itemView) {
super(itemView);
profileImage = (ImageView) itemView.findViewById(R.id.profileImage);
full_name = (TextView) itemView.findViewById(R.id.full_name);
user_name = (TextView) itemView.findViewById(R.id.user_name);
user_id = (TextView) itemView.findViewById(R.id.user_id);
}
}
public SearchAdapter(Context context, ArrayList<String> fullNameList, ArrayList<String> userNameList, ArrayList<String> userIdList, ArrayList<String> profileImageList) {
this.context = context;
this.fullNameList = fullNameList;
this.userNameList = userNameList;
this.userIdList = userIdList;
this.profileImageList = profileImageList;
}
#Override
public SearchAdapter.SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.search_list_item, parent, false);
return new SearchAdapter.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(final SearchViewHolder holder, int position) {
holder.full_name.setText(fullNameList.get(position));
holder.user_name.setText(userNameList.get(position));
holder.user_id.setText(userIdList.get(position));
Glide.with(context).load(profileImageList.get(position)).into(holder.profileImage);
}
#Override
public int getItemCount() {
return fullNameList.size();
}
}
User Profile Class:
public class UserProfile extends AppCompatActivity {
private CircleImageView u_pro_img;
private TextView u_user_name, u_fullname, u_bio, u_fricou;
private Button add_fri;
private DatabaseReference mUDBR;
private TextView user_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
u_pro_img = (CircleImageView) findViewById(R.id.u_pro_img);
u_user_name = (TextView) findViewById(R.id.u_user_name);
u_fullname = (TextView) findViewById(R.id.u_fullname);
u_bio = (TextView) findViewById(R.id.u_bio);
u_fricou = (TextView) findViewById(R.id.u_fricou);
add_fri = (Button) findViewById(R.id.add_fri);
mUDBR = FirebaseDatabase.getInstance().getReference();
user_id = (TextView) findViewById(R.id.user_id);
}
}
I just want to pass the user id key to user profile activity when the user selects the person from the results. I hope you understand me.

Use below code to send userId to ProfileActivity(Here sending data from SearchAdapter class )
#Override
public void onBindViewHolder(final SearchViewHolder holder, int position) {
holder.full_name.setText(fullNameList.get(position));
holder.user_name.setText(userNameList.get(position));
holder.user_id.setText(userIdList.get(position));
Glide.with(context).load(profileImageList.get(position)).into(holder.profileImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//for sending data UserProfile
Intent intent = new Intent(context,UserProfile.class);
intent.putExtra("USER_ID",String.valueOf(userIdList.get(position)));
context.startActivity(intent);
}
});
}
on your UserProfile.cass get userId by following way :
String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
u_pro_img = (CircleImageView) findViewById(R.id.u_pro_img);
u_user_name = (TextView) findViewById(R.id.u_user_name);
u_fullname = (TextView) findViewById(R.id.u_fullname);
u_bio = (TextView) findViewById(R.id.u_bio);
u_fricou = (TextView) findViewById(R.id.u_fricou);
add_fri = (Button) findViewById(R.id.add_fri);
mUDBR = FirebaseDatabase.getInstance().getReference();
user_id = (TextView) findViewById(R.id.user_id);
//Getting data here UserId
userId = getIntent().getStringExtra("USER_ID","");
Toast toast=Toast.makeText(getApplicationContext(),"USER ID "+userId ,Toast.LENGTH_SHORT);
}}

Related

Data retrieved from firebase not showing up in recyclerview

I am fairly new in android studio. So when I click on the floating action button, put in new data, it stores the data in my firebase database but displays blank screen and a notification that "budget item added successfully" and the app does not crash either. I'm not sure what I did wrong in the code or maybe the codes were not properly typed. Any help would be appreciated very much.
Activity class.
public class TodaySpendingActivity extends AppCompatActivity {
private Toolbar toolbar;
private TextView totalAmountSpentOn;
private ProgressBar progressBar;
private RecyclerView recyclerView;
private FloatingActionButton fab;
private ProgressDialog loader;
private FirebaseAuth mAuth;
private String onlineUserId = "";
private DatabaseReference expensesRef;
private TodayItemAdapter todayItemAdapter;
private List<Data> myDataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_spending);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar((androidx.appcompat.widget.Toolbar)toolbar);
getSupportActionBar().setTitle("Today's Spending");
totalAmountSpentOn = findViewById(R.id.totalAmountSpentOn);
progressBar = findViewById(R.id.progressBar);
fab = findViewById(R.id.fab);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
onlineUserId = mAuth.getCurrentUser().getUid();
expensesRef = FirebaseDatabase.getInstance().getReference("expenses").child(onlineUserId);
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
myDataList = new ArrayList<>();
todayItemAdapter = new TodayItemAdapter( TodaySpendingActivity.this, myDataList);
recyclerView.setAdapter(todayItemAdapter);
readItems();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addItemSpentOn();
}
private void addItemSpentOn() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(TodaySpendingActivity.this);
LayoutInflater inflater = LayoutInflater.from(TodaySpendingActivity.this);
View myView = inflater.inflate(R.layout.input_layout, null);
myDialog.setView(myView);
final AlertDialog dialog = myDialog.create();
dialog.setCancelable(false);
final Spinner itemSpinner = myView.findViewById(R.id.itemspinner);
final EditText amount = myView.findViewById(R.id.amount);
final EditText note = myView.findViewById(R.id.note);
final Button cancel = myView.findViewById(R.id.cancel);
final Button save = myView.findViewById(R.id.save);
note.setVisibility(View.VISIBLE);
save.setOnClickListener(view -> {
String Amount = amount.getText().toString();
String Item = itemSpinner.getSelectedItem().toString();
String notes = note.getText().toString();
if(TextUtils.isEmpty(Amount)){
amount.setError("Please input an amount!");
return;
}
if (Item.equals("Select item")){
Toast.makeText(TodaySpendingActivity.this,"Select a valid item", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(notes)){
note.setError("Note is Requires");
return;
}
else {
loader.setMessage("Adding a budget item");
loader.setCanceledOnTouchOutside(false);
loader.show();
String id = expensesRef.push().getKey();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
String date = dateFormat.format(cal.getTime());
MutableDateTime epoch = new MutableDateTime();
epoch.setDate(0);
DateTime now = new DateTime();
Months months = Months.monthsBetween(epoch, now);
Data data = new Data(Item, date, id, notes, Integer.parseInt(Amount), months.getMonths());
expensesRef.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(TodaySpendingActivity.this, "Budget item added successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(TodaySpendingActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
loader.dismiss();
}
});
}
dialog.dismiss();
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
private void readItems() {
Query query = expensesRef.orderByChild("month").equalTo(new DateTime().getMonthOfYear());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
myDataList.clear();
for (DataSnapshot ds: snapshot.getChildren()){
Data data = ds.getValue(Data.class);
myDataList.add(data);
}
todayItemAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
int totalAmount = 0;
for (int i = 0; i < myDataList.size(); i++){
totalAmount += myDataList.get(i).getAmount();
String stTotal = String.valueOf(totalAmount);
totalAmountSpentOn.setText(stTotal);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Adapter Class.
public class TodayItemAdapter extends RecyclerView.Adapter<TodayItemAdapter.ViewHolder>{
private Context mContext;
private List<Data> myDataList;
private String post_key= "";
private String item= "";
private String note="";
private int amount = 0;
public TodayItemAdapter(Context mContext, List<Data> myDataList) {
this.mContext = mContext;
this.myDataList = myDataList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.retrieve_layout, parent, false);
return new TodayItemAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Data data = myDataList.get(position);
holder.item.setText("Item: "+ data.getItem());
holder.amount.setText("Amount: "+ data.getAmount());
holder.date.setText("On: "+ data.getDate());
holder.note.setText("Note: "+ data.getNotes());
switch (data.getItem()){
case "Transport":
holder.imageView.setImageResource(R.drawable.ic_transport);
break;
case "Food":
holder.imageView.setImageResource(R.drawable.ic_food);
break;
case "House":
holder.imageView.setImageResource(R.drawable.ic_house);
break;
case "Entertainment":
holder.imageView.setImageResource(R.drawable.ic_entertainment);
break;
case "Education":
holder.imageView.setImageResource(R.drawable.ic_education);
break;
case "Charity":
holder.imageView.setImageResource(R.drawable.ic_charity);
break;
case "Clothing":
holder.imageView.setImageResource(R.drawable.ic_clothing);
break;
case "Health":
holder.imageView.setImageResource(R.drawable.ic_health);
break;
case "Personal":
holder.imageView.setImageResource(R.drawable.ic_personal);
break;
case "Other":
holder.imageView.setImageResource(R.drawable.ic_other);
break;
}
}
#Override
public int getItemCount() {
return myDataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView item, amount, date, note;
public ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item = itemView.findViewById(R.id.item);
amount = itemView.findViewById(R.id.amount);
date = itemView.findViewById(R.id.date);
note = itemView.findViewById(R.id.note);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
First check addValueEventListener is called when new data is stored
if yes then change code as mentioned below and try again
in readItems method
From
todayItemAdapter.notifyDataSetChanged();
To
todayItemAdapter.addData(myDataList);
add method in TodayItemAdapter class as mentioned below
public void addData(List< Data> list){
myDataList.addAll(list);
notifyDataSetChanged();
}

Recycler adapter is not showing data

I am using Firebase to create an app where users can sign up for a class and then view them. I am using the same recycler adapter and objects for the activities that show the classes and the activity that shows the users classes under their uid. When I run the app, the classes show up that I have input into Firebase, but the activity that shows the users' classes shows a blank cardview(same code used). The error is:`
No setter/field for room_number2 found on class com.samuelford48gmail.thsconnect.Class_model
No setter/field for date_clasname2 found on class com.samuelford48gmail.thsconnect.Class_model
No setter/field for teacher2 found on class com.samuelford48gmail.thsconnect.Class_model
My code for the fragment that shows the users' classes:
public class home_fragment extends Fragment implements View.OnClickListener {
private Button button;
//DatabaseReference dref;
//ListView listview2;
//ArrayList<String> list=new ArrayList<>();
private FirebaseDatabase database;
private DatabaseReference myRef;
private List<Listdata> list;
private RecyclerView recyclerview;
public home_fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment, container, false);
//FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
//if(fbUser == null) { Intent intent = new Intent(getContext(), LoginActivity.class);
// startActivity(intent);}
button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(this);
recyclerview = (RecyclerView) view.findViewById(R.id.rview);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<>();
// 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();
String class_key = new_class.getUid();
Listdata listdata = new Listdata(nameofclass, teacherofclass, roomnumberofclass, class_key);
//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();
}
RecyclerviewAdapter2 recycler = new RecyclerviewAdapter2(list);
RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
recyclerview.setLayoutManager(layoutmanager);
recyclerview.setItemAnimator(new DefaultItemAnimator());
recyclerview.setAdapter(recycler);
}
#Override
public void onCancelled(DatabaseError error) {
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).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());
}
});
return view;
}
#Override
public void onClick(View view) {
signout();
//startActivity(new Intent(home_fragment.this,
LoginActivity.class));
}
public void signout(){
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getContext(), LoginActivity.class);
startActivity(intent);
}
}
Here is the code for my Recycler Adapter class:
public class RecyclerviewAdapter2 extends RecyclerView.Adapter<RecyclerviewAdapter2.MyHolder>{
List<Listdata> listdata;
public RecyclerviewAdapter2(List<Listdata> listdata) {
this.listdata = listdata;
}
#Override
public RecyclerviewAdapter2.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_class_model,parent,false);
RecyclerviewAdapter2.MyHolder myHolder = new RecyclerviewAdapter2.MyHolder(view);
return myHolder;
}
public void onBindViewHolder(RecyclerviewAdapter2.MyHolder holder, final int position) {
final Listdata data = listdata.get(position);
holder.vdate_class.setText(data.getDate_class());
holder.vteacher.setText(data.getTeacher());
holder.vrnumber.setText(data.getRnumber());
//System.out.println(data.getDate_class2());
holder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick( final View view) {
Context context = view.getContext();
Intent intent = new Intent(context, test_for_science_add_class.class);
intent.putExtra("date_class", listdata.get(position).getDate_class());
intent.putExtra("teacher", listdata.get(position).getTeacher());
intent.putExtra("room_number", listdata.get(position).getRnumber());
intent.putExtra("post_key", listdata.get(position).getUid());
context.startActivity(intent);
}
});
}
#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.teacher);
vrnumber = (TextView) itemView.findViewById(R.id.room_number);
}
}
}
Here is my Class_model code:
public class Class_model {
//String subject;
String date_clasname;
String teacher;
String room_number;
String uid;
public Class_model(){};
public Class_model(String date_classname, String teacher, String room_number, String uid){
this.date_clasname = date_classname;
this.teacher = teacher;
this.room_number = room_number;
this.uid = uid;
}
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;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
Here is my code for the Listdata class:
public class Listdata {
String date_class;
String teacher;
String rnumber;
String uid;
public Listdata(String date_class, String teacher, String rnumber, String uid) {
this.date_class = date_class;
this.teacher = teacher;
this.rnumber = rnumber;
this.uid = uid;
}
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;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
My Firebase structure:
"Technology" : {
"-LgxmDqmlPZnCOEyjBww" : {
"date_clasname" : "technology",
"room_number" : "d",
"teacher" : "f"
}
},
"Users" : {
"NnJlSVeqGXhJ2Nab2bhjr0HIpku2" : {
"Classes" : {
"-LhM7iyYhmwvtDvtLE-Z" : {
"date_clasname2" : "technology",
"room_number2" : "d",
"teacher2" : "f"
},
"-LhM7k0uI_eY31nQnnro" : {
"date_clasname2" : "other",
"room_number2" : "d",
"teacher2" : "f"
},
"-LhM87eT7kv7KL1JHryM" : {
"date_clasname2" : "March 5",
"room_number2" : "101",
"teacher2" : "pence"
}
},
"email" : "samuelford48#gmail.com",
"grade" : "12",
"name" : "Samuel Ford"
},
Here is my code for the activity that happens when the user clicks on one of the recycler view items:
public class test_for_science_add_class extends AppCompatActivity {
private Button add_class;
private FirebaseDatabase database;
private DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_for_science_addd_class);
final String date_class2 = getIntent().getStringExtra("date_class");
final String teacher = getIntent().getStringExtra("teacher");
final String room_number = getIntent().getStringExtra("room_number");
final String post_key = getIntent().getStringExtra("post_key");
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
//String name = getIntent().getExtra("date_class");
//String city = getIntent().getExtra("City");
//System.out.println(value);
TextView display_class_name = (TextView) findViewById(R.id.date_tv2);
display_class_name.setText(date_class2);
TextView display_teacher = (TextView) findViewById(R.id.teacher_tv2);
display_teacher.setText(teacher);
TextView display_room_number = (TextView) findViewById(R.id.rn_tv2);
display_room_number.setText(room_number);
add_class = (Button) findViewById(R.id.add_class_2);
add_class.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Class_model_without_uid new_class_to_user_uid = new Class_model_without_uid(date_class2, teacher, room_number);
myRef.push().setValue(new_class_to_user_uid);
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
}
});
}
}
In my activity that handles clicks on a recycler item, I was calling the wrong object class when pushing to Firebase.
Incorrect code:
Class_model_without_uid new_class_to_user_uid = new Class_model_without_uid(date_class2, teacher, room_number);
myRef.push().setValue(new_class_to_user_uid);
Correct code:
Class_model new_class_to_user_uid = new Class_model(date_class, teacher, room_number, null);
myRef.push().setValue(new_class_to_user_uid);

How to make FirestoreRecyclerAdapter work not with model class?

I mean how to make the adapter work not with the model class, but with the already created ArrayList (randomPlaceList)? I take 20 records from my Firestore and put 3 random of them to the ArrayList(randomPlaceList). And now, I want that my adapter connect ViewHolder object not with the model class(Places.class), but with this early created ArrayList(randomPlaceList), where I have already 3 random records..
RecycleView class:
public class Myactivity extends AppCompatActivity {
public RecyclerView mResultList;
public FirebaseFirestore mFirestore;
public com.google.firebase.firestore.Query query;
public FirestoreRecyclerAdapter<Places, PlaceViewHolder> firestoreRecyclerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycle_activity);
mResultList = findViewById(R.id.list_result);
Boolean l_check1 = getIntent().getExtras().getBoolean("1");
Boolean l_check2 = getIntent().getExtras().getBoolean("2");
Boolean l_check3 = getIntent().getExtras().getBoolean("3");
mFirestore = FirebaseFirestore.getInstance();
if (l_check1) {
query = mFirestore.collection("Places").whereEqualTo("colour", "1").limit(20);
//QUESTION START HERE
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
int placeCount = placesList.size();
int randomNumber = new Random().nextInt(placeCount);
//THIS ARRAYLIST I WANT TO USE INSTEAD THE PLACES.CLASS
List<Places> randomPlaceList = new ArrayList<>();
for (int i=1; i<=3; i++) {
randomPlaceList.add(placesList.get(randomNumber));
}
}
}
});
} else if (l_check2) {
query = mFirestore.collection("Places").whereEqualTo("colour", "2").limit(3);
} else if (l_check3) {
query = mFirestore.collection("Places").whereEqualTo("colour", "3").limit(3);
}
mResultList.setLayoutManager(new LinearLayoutManager(this));
FirestoreRecyclerOptions<Places> options = new FirestoreRecyclerOptions.Builder<Places>()
.setQuery(query, Places.class)
.build();
firestoreRecyclerAdapter = new FirestoreRecyclerAdapter<Places, PlaceViewHolder>(options) {
#Override
protected void onBindViewHolder(PlaceViewHolder holder, int position, Places model) {
holder.setDetails(getApplicationContext(), model.getName(), model.getImage());
}
#Override
public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
return new PlaceViewHolder(view);
}
};
mResultList.setAdapter(firestoreRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
firestoreRecyclerAdapter.startListening();
}
class PlaceViewHolder extends RecyclerView.ViewHolder {
View mView;
public PlaceViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context context, String placeName, String placeImage) {
final TextView place_Name = mView.findViewById(R.id.text_image_id);
ImageView place_Image = mView.findViewById(R.id.image_id);
place_Name.setText(placeName);
Glide.with(context).load(placeImage).into(place_Image);
place_Name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Card_activity.class);
intent.putExtra("qwerty", place_Name.getText());
startActivity(intent);
}
});
}
}
#Override
protected void onStop() {
super.onStop();
if (firestoreRecyclerAdapter != null) {
firestoreRecyclerAdapter.stopListening();
}
}
}
And that model class, that used in OnCreate method, for query, but I need to use in Adapter, randomPlaceList to take 3 records, that already put earlier in it. In other words, use 2 model class, if I can say so..:
My Model class:
public class Places {
private String image, name;
public Places() { }
public Places(String image, String name) {
this.image = image;
this.name = name;
}
public String getImage() { return image; }
public String getName() { return name; }
}
EDITED WITH LISTVIEW:
MyListAdaper:
class MyListAdapter extends ArrayAdapter {
public MyListAdapter(Context context, int resource,List<Places> randomPLaceList) {
super(context, 0, randomPLaceList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_list, parent, false);
}
TextView place_Name = convertView.findViewById(R.id.text_image_id);
ImageView place_Image = convertView.findViewById(R.id.image_id);
Places places = (Places) getItem(position);
place_Name.setText(places.getName());
Glide.with(getContext()).load(places.getImage()).into(place_Image);
return convertView;
}
}
ListViewPlaces.class:
public class ListViewPlaces extends AppCompatActivity {
public ListView mListView;
public MyListAdapter myListAdapter;
public FirebaseFirestore mFirestore;
public Query query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_places);
Boolean l_check1 = getIntent().getExtras().getBoolean("1");
mFirestore = FirebaseFirestore.getInstance();
if (l_check1) {
query = mFirestore.collection("Places").whereEqualTo("meet", "1").whereEqualTo("cash", "1").limit(7);
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
//mListView = findViewById(R.id.place_list);
//mListView.setAdapter(myListAdapter);
final int placeCount = placesList.size();
final Random randomGenerator = new Random();
List<Places> randomPlaceList = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
randomPlaceList.add(placesList.get(randomGenerator.nextInt(placeCount)));
}
ListView mListView = (ListView) findViewById(R.id.place_list);
MyListAdapter mListAdapter = new MyListAdapter(this, randomPlaceList);
mListView.setAdapter(mListAdapter);
}
}
});
}
}
}
Error:
error: constructor MyListAdapter in class MyListAdapter cannot be
applied to given types; required: Context,int,List found:
>,List reason:
actual and formal argument lists differ in length

SearchView filteredlist not showing the list of recyclerview data

Hello can I ask why my search view isn't filtering the list of data when searching on the fragments recyclerview and Also when I click the fragments activity again after trying to search it would result into an error
java.lang.NullPointerException: Attempt to invoke interface method
'void java.util.List.add(int, java.lang.Object)' on a null object
reference at
com.google.firebase.ikuzou.database.MemberDetailAdapter$UserChildEventListener.onChildAdded(MemberDetailAdapter.java:73)
RecyclerView Adapter
public class MemberDetailAdapter extends RecyclerView.Adapter<MemberDetailAdapter.ViewHolder> implements Filterable {
private List<User1> mUser,nUser;
private Callback mCallback;
private DatabaseReference userref;
public MemberDetailAdapter(Callback callback) {
mCallback = callback;
mUser = new ArrayList<>();
userref = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users");
userref.addChildEventListener(new UserChildEventListener());
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()){
mUser=nUser;
}else {
List<User1> filteredList = new ArrayList<>();
for (User1 row : nUser){
if (row.getFirst().toLowerCase().contains(charString.toLowerCase()) || row.getSecond().contains(charSequence)){
filteredList.add(row);
}
}
mUser=filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mUser;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
}
};
}
class UserChildEventListener implements ChildEventListener{
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User1 user = dataSnapshot.getValue(User1.class);
user.setKey(dataSnapshot.getKey());
mUser.add(0,user);
notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String key = dataSnapshot.getKey();
User1 updatedUser = dataSnapshot.getValue(User1.class);
for (User1 user : mUser){
if (user.getKey().equals(key)){
user.setValues(updatedUser);
notifyDataSetChanged();
return;
}
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String key = dataSnapshot.getKey();
for(User1 user: mUser){
if (user.getKey().equals(key)){
mUser.remove(user);
break;
}
}
notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final User1 user = mUser.get(position);
holder.mfirstNameTextView.setText(user.getFirst());
holder.msecondNameTextView.setText(user.getSecond());
holder.mnumberTextView.setText(user.getNumber());
holder.mgenderTextView.setText(user.getGender());
holder.mEmailTextView.setText(user.getEmail());
holder.mDateTextView.setText(user.getDate());
holder.mTypeTextView.setText(user.getType());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onEdit(user);
}
});
}
public void remove(User1 user) {
//TODO: Remove the next line(s) and use Firebase instead
userref.child(user.getKey()).removeValue();
}
#Override
public int getItemCount() {
if(mUser==null){
Log.v("LOG","Warn, null filteredData");
return 0;
}else{
return mUser.size();
}
}
public void add(User1 user) {
//TODO: Remove the next line(s) and use Firebase instead
userref.push().setValue(user);
}
public void update(User1 user, String newFirst,String newSecond, String newNumber, String newGender,String newDate) {
//TODO: Remove the next line(s) and use Firebase instead
user.setFirst(newFirst);
user.setSecond(newSecond);
user.setNumber(newNumber);
user.setGender(newGender);
user.setDate(newDate);
userref.child(user.getKey()).setValue(user);
}
public interface Callback {
public void onEdit(User1 user);
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView mfirstNameTextView;
private TextView msecondNameTextView;
private TextView mnumberTextView;
private TextView mgenderTextView;
private TextView mEmailTextView;
private TextView mDateTextView;
private TextView mTypeTextView;
public ViewHolder(View itemView) {
super(itemView);
mfirstNameTextView = (TextView) itemView.findViewById(R.id.firstnameTxt);
msecondNameTextView = (TextView) itemView.findViewById(R.id.lastnameTxt);
mnumberTextView = (TextView) itemView.findViewById(R.id.numberTxt);
mgenderTextView = (TextView) itemView.findViewById(R.id.genderTxt);
mEmailTextView = (TextView) itemView.findViewById(R.id.emailTxt);
mDateTextView = (TextView) itemView.findViewById(R.id.dateTxt);
mTypeTextView = (TextView) itemView.findViewById(R.id.typeTxt);
}
}
My Fragment code
public class memberFragment extends Fragment implements MemberDetailAdapter.Callback, SearchView.OnQueryTextListener {
private ListView mylistView;
private DatabaseReference db;
private Firebasehelper helper;
private CustomAdapter adapter;
private ListView lv;
private com.google.firebase.ikuzou.database.MemberDetailAdapter mAdapter;
public memberFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_member2, container, false);
mAdapter = new com.google.firebase.ikuzou.database.MemberDetailAdapter(this);
setHasOptionsMenu(true);
RecyclerView view1 = (RecyclerView) view.findViewById(R.id.recycler_view);
view1.setLayoutManager(new LinearLayoutManager(getContext()));
view1.setHasFixedSize(true);
view1.setAdapter(mAdapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
super.onCreateOptionsMenu(menu, inflater);
}
private void showAddEditDialog(final User1 user) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getString(user == null ? R.string.dialog_add_title : R.string.dialog_edit_title));
View view = getLayoutInflater().inflate(R.layout.input_dialog, null, false);
builder.setView(view);
final EditText firstnameEditText = (EditText) view.findViewById(R.id.firstnameEditText);
final EditText secondnameEditText = (EditText) view.findViewById(R.id.secondnameEditText);
final EditText numberEditText = (EditText) view.findViewById(R.id.numberEditText);
final EditText genderEditText = (EditText) view.findViewById(R.id.genderEditText);
final EditText emailEditText = (EditText) view.findViewById(R.id.emailEditText);
final EditText dateEditText = (EditText) view.findViewById(R.id.dateEditText);
final TextView typeEditText = (TextView) view.findViewById(R.id.typeEditText);
if (user != null) {
// pre-populate
firstnameEditText.setText(user.getFirst());
secondnameEditText.setText(user.getSecond());
numberEditText.setText(user.getNumber());
genderEditText.setText(user.getGender());
emailEditText.setText(user.getEmail());
dateEditText.setText(user.getDate());
typeEditText.setText(user.getType());
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// empty
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// empty
}
#Override
public void afterTextChanged(Editable s) {
String firstname = firstnameEditText.getText().toString();
String secondname = secondnameEditText.getText().toString();
String number = numberEditText.getText().toString();
String gender = genderEditText.getText().toString();
String date = dateEditText.getText().toString();
mAdapter.update(user, firstname,secondname,number,gender,date );
}
};
firstnameEditText.addTextChangedListener(textWatcher);
secondnameEditText.addTextChangedListener(textWatcher);
numberEditText.addTextChangedListener(textWatcher);
genderEditText.addTextChangedListener(textWatcher);
emailEditText.addTextChangedListener(textWatcher);
dateEditText.addTextChangedListener(textWatcher);
}
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (user == null) {
String firstname = firstnameEditText.getText().toString();
String secondname = secondnameEditText.getText().toString();
String number = numberEditText.getText().toString();
String gender = genderEditText.getText().toString();
String email = emailEditText.getText().toString();
String date = dateEditText.getText().toString();
mAdapter.add(new User1(firstname,secondname,number,gender, date, email));
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.create().show();
// Inflate the layout for this fragment
}
#Override
public void onEdit(final User1 user) {
showAddEditDialog(user);
}
#Override
public boolean onQueryTextSubmit(String query) {
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
mAdapter.getFilter().filter(query);
return false;
}
Before all of this happen I have a
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()'
But changing my getItemcount into
public int getItemCount() {
if(mUser==null){
Log.v("LOG","Warn, null filteredData");
return 0;
}else{
return mUser.size();
}
}
From
public int getItemCount() {
return mUser.size();
}
Fixed the problem.

Check if all items in RecyclerView have the same value (google Firestore)

I need to chceck if all items on adapter have a boolean value = true
Then based on result i have to change floatingActionButton color.
I have no idea how to do it.
Here is my Adapter:
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference basementReference = db.collection("basement");
private TableAdapter tableAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton basement = findViewById(R.id.button_basement);
basement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
setUpRecyclerView();
}
private void setUpRecyclerView(){
final Query query = basementReference.orderBy("tableNumber",Query.Direction.ASCENDING);
FirestoreRecyclerOptions<Table> options = new FirestoreRecyclerOptions.Builder<Table>()
.setQuery(query, Table.class)
.build();
tableAdapter = new TableAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(tableAdapter); tableAdapter.setOnItemClickListener(new TableAdapter.OnItemCLickListener() {
#Override
public void onItemClick(final DocumentSnapshot documentSnapshot, int position) {
Table table = documentSnapshot.toObject(Table.class);
if(table.isTableOccupied()){
basementReference.document(documentSnapshot.getId()).update("tableOccupied",false).addOnCompleteListener(new OnCompleteListener<Void>() {
}else {
basementReference.document(documentSnapshot.getId()).update("tableOccupied",true).addOnCompleteListener(new OnCompleteListener<Void>() {
}
#Override
protected void onStart() {
super.onStart();
tableAdapter.startListening();
}
please help. i tthink i need to do it in my adapter class, but if there is other solution i'll be glad to follow :)
tableAdapter class:
class TableAdapter extends FirestoreRecyclerAdapter {
public TableAdapter(#NonNull FirestoreRecyclerOptions<Table> options) {
super(options);
}
private OnItemCLickListener onItemCLickListener;
private int occupiedMarker = 0;
#Override
protected void onBindViewHolder(#NonNull TableHolder holder, int position, #NonNull Table model) {
holder.textViewTableNumber.setText(model.getTableNumber());
holder.textViewTableSeats.setText(model.getTableSeats());
holder.textViewTableOccupied.setText(String.valueOf(model.isTableOccupied()));
}
#NonNull
#Override
public TableHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_table,parent,false);
return new TableHolder(v);
}
class TableHolder extends RecyclerView.ViewHolder{
TextView textViewTableNumber;
TextView textViewTableSeats;
TextView textViewTableOccupied;
public TableHolder(#NonNull View itemView) {
super(itemView);
textViewTableNumber = itemView.findViewById(R.id.text_view_table_number);
textViewTableSeats = itemView.findViewById(R.id.text_view_table_seats);
textViewTableOccupied = itemView.findViewById(R.id.text_view_table_occupied);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && onItemCLickListener!=null){
onItemCLickListener.onItemClick( getSnapshots().getSnapshot(position), position );
}
}
});
}
}
public interface OnItemCLickListener {
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemCLickListener onItemClickListener){
this.onItemCLickListener = onItemClickListener;
}
}

Categories