Data retrieved from firebase not showing up in recyclerview - java

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();
}

Related

There is no compilation error but when running the code clicking the comment button, it is not leading to the activity I want

I did the code below, used the adapter to show the list, and a button to add a comment to list item, it shows the logcat "ViewPostIme pointer 0 and ViewPostIme pointer 1", upon clicking the comment button.
Upon compilation it doesn't show any error, I tried to use many references via google but nothing works out.
My basic idea is to call the comment button with an associated list item to perform the comment activity.
Adapter class
public class PostsAdapter extends FirestoreRecyclerAdapter<PostsModel, PostsAdapter.PostsHolder> {
private OnItemClickListener listener;
private View.OnClickListener buttonListener;
private String id;
private static final String TAG = "DocSnippets";
public PostsAdapter(#NonNull FirestoreRecyclerOptions<PostsModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull PostsHolder holder, int position, #NonNull PostsModel model) {
//retrieve the fields here
holder.textViewDescription.setText(model.getPostContent());
holder.textViewPriority.setText(String.valueOf(model.getSpinnerC()));
holder.textViewPriority.setText(String.valueOf(model.getTimestamp()));
}
#NonNull
#Override
public PostsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list_layout,
parent, false);
return new PostsHolder(v);
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
public void setOnClickListener(OnClickListener postKey) {
}
class PostsHolder extends RecyclerView.ViewHolder {
//first declare here the elements to be displayed in the cardview.
TextView textViewTitle;
TextView textViewDescription;
TextView textViewPriority;
Button commentsbutton;
public PostsHolder(final View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.post_etPostTitle);
textViewDescription = itemView.findViewById(R.id.post_description);
textViewPriority = itemView.findViewById(R.id.post_time);
commentsbutton = itemView.findViewById(R.id.commenting_button);
commentsbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && buttonListener != null) {
buttonListener.onClick(itemView);
}
}
});
}
}
public interface OnClickListener
{
void OnClickListener(DocumentSnapshot documentSnapshot, int position);
}
public void setOnClickListener(View.OnClickListener onClickListener) {
this.buttonListener = onClickListener;
}
public interface OnItemClickListener {
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
Fragment Class
public class HomeFragment extends Fragment {
RelativeLayout mParent;
//FloatingActionButton addButton;
private static final String TAG = "DocSnippets";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference PostsRef = db.collection("posts");
private PostsAdapter adapter;
private FirestoreRecyclerOptions options;
private FirebaseAuth mAuth;
private String mUserId, id;
private Button commentsbutton;
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard
View view = inflater.inflate(R.layout.fragment_home, container, false);
final FragmentActivity c = getActivity();
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
Query query = PostsRef.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<PostsModel> options = new FirestoreRecyclerOptions.Builder<PostsModel>()
.setQuery(query, PostsModel.class)
.build();
adapter = new PostsAdapter(options);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(c));
recyclerView.setAdapter(adapter);
commentsbutton = (Button) view.findViewById(R.id.commenting_button);
mParent =view.findViewById(R.id.relative_home);
mAuth = FirebaseAuth.getInstance();
mUserId = mAuth.getUid();
adapter.setOnItemClickListener(new PostsAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
PostsModel note = documentSnapshot.toObject(PostsModel.class);
id = documentSnapshot.getId();
String path = documentSnapshot.getReference().getPath();
Log.d(TAG, "String post Id is: " + id);
}
});
adapter.setOnClickListener(new PostsAdapter.OnClickListener() {
#Override
public void OnClickListener(DocumentSnapshot documentSnapshot, int position) {
PostsModel note = documentSnapshot.toObject(PostsModel.class);
id = documentSnapshot.getId();
String path = documentSnapshot.getReference().getPath();
Log.d(TAG, "String post Id is: " + id);
Intent toCommentActivity = new Intent(getContext(), CommentActivity.class);
toCommentActivity.putExtra("PostKey", id);
getContext().startActivity(toCommentActivity);
}
});
return view;
}
private String getTime(long timestamp){
long ts = timestamp*1000;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
String time = sdf.format(new Date(ts));
return time;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}

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);

Android studio select search results

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

Display no. of items of a recyclerview in a textview in android studio

I want to display number of total items of my recyclerview in a textview. If new item is added or deleted that textview should be update. And also calculate total price of items in a list of Items in a recyclerview and display in a textview below recyclerview list.
Below is my recyclerview adapter:
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
private List<ProductView.Data> productData = Collections.emptyList();
static List<ProductModel> productModelList;
static Context context;
DatabaseHandler mDatabaseHandler;
public CartAdapter(Context context, List<ProductModel> dbList ){
this.productModelList = new ArrayList<ProductModel>();
this.context = context;
this.productModelList = dbList;
mDatabaseHandler = new DatabaseHandler( context );
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View cartListView = inflater.inflate(R.layout.list_item_cart, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context,cartListView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvProductName.setText(productModelList.get(position).getTitle());
holder.tvProductPrice.setText(productModelList.get(position).getPrice());
Glide
.with(context)
.load(productModelList.get(position).getImageUrl())
.into(holder.imgProduct);
// holder.tvProductStatus.setText(productModelList.get(position).getIsAvailable());
holder.tvSize.setText(productModelList.get(position).getSize());
holder.tvProductQuantity.setText(Integer.toString(productModelList.get(position).getQuantity()));
holder.tvColor.setText(productModelList.get(position).getColor());
//holder.tvMaterial.setText(productModelList.get(position).getMaterial());
holder.imgDelete.setClickable(true);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String idForDelete = String.valueOf(productModelList.get(position).getVariantId());
mDatabaseHandler.deleteARow(idForDelete);
productModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,productModelList.size());
}
});
}
#Override
public int getItemCount() {
return productModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice, tvProductQuantity,tvColor,
tvSize;
ImageView imgProduct;
ImageButton imgDelete;
Context context;
public ViewHolder(Context mContext, View itemView) {
super(itemView);
this.tvProductName = (TextView) itemView.findViewById(R.id.tv_cart_product_name);
this.tvProductPrice = (TextView) itemView.findViewById(R.id.tv_cart_product_price);
this.tvProductQuantity = (TextView) itemView.findViewById(R.id.tv_cart_product_Quantity);
this.imgProduct = (ImageView) itemView.findViewById(R.id.img_cart_item_product);
this.tvColor = (TextView)itemView.findViewById(R.id.tv_color);
this.tvSize = (TextView) itemView.findViewById(R.id.tv_size);
this.imgDelete = (ImageButton) itemView.findViewById(R.id.img_cart_delete);
// store the context ///
this.context = mContext;
}
}
and java Class:
public class CartActivity extends AppCompatActivity {
DatabaseHandler helper;
List<ProductModel> dbList;
RecyclerView mRecyclerView;
Toolbar toolbar;
Button btnCheckout, btnContinueShopping;
TextView tvTotalNoOfItems, tvTotalPrice;
String p;
String i;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
p = getIntent().getStringExtra("variant_id");
i = getIntent().getStringExtra("product_id");
Bundle extras = getIntent().getExtras();
if (extras != null) {
p = extras.getString("variant_id");
i= extras.getString("product_id");
}
toolbar = (Toolbar) findViewById(R.id.customToolBar);
setSupportActionBar(toolbar);
setTitle("Check-out");
toolbar.setTitleTextColor(Color.BLACK);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
helper = new DatabaseHandler(this);
dbList= new ArrayList<ProductModel>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.rv_cart_item_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CartAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
tvTotalNoOfItems = (TextView)findViewById(R.id.tvTotalCartItems);
tvTotalPrice = (TextView)findViewById(R.id.tvTotalCartItemsPrice);
String totalPrice = "";
for (int i = 0; i<dbList.size(); i++)
{
totalPrice = totalPrice + dbList.get(i).getPrice().toString();
}
tvTotalPrice.setText(totalPrice);
btnContinueShopping = (Button)findViewById(R.id.btnBackToProductActivity);
btnContinueShopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCOllectionActivity = new Intent(CartActivity.this, CollectionActivity.class);
startActivity(launchCOllectionActivity);
finish();
}
});
btnCheckout = (Button)findViewById(R.id.btn_checkout);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCheckoutActivity = new Intent(CartActivity.this,CheckoutActivity.class);
startActivity(launchCheckoutActivity);
}
});
}
}
First, add following getter to your adapter:
public List<ProductModel> getItems(){
return productModelList;
}
Then, you can subscribe on adapter data change and do the following:
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged () {
tvTotalNoOfItems.setText(mAdapter.getItemCount());
String totalPrice = "";
for (int i = 0; i < ((CartAdapter)mAdapter).getItems().size(); i++) {
totalPrice = totalPrice + ((CartAdapter)mAdapter).getItems().get(i).getPrice().toString();
}
tvTotalPrice.setText("" + totalPrice);
}
});
just add this line below the adapter set line
tvTotalNoOfItems.setText(mAdapter.getCount());
and add this into you adapter class where you delete action perform
String totalPrice = "";
((CartActivity)context).tvTotalNoOfItems.setText(getCount());
for (int i = 0; i<productModelList.size(); i++)
{
totalPrice = totalPrice + productModelList.get(i).getPrice().toString();
}
((CartActivity)context).tvTotalPrice.setText(""+totalPrice);
Just public you textview like this
public TextView tvTotalNoOfItems, tvTotalPrice;

Converting a cursor to list error

I made a question earlier about how to swap from listview to a recyclerview. However I noticed that with my change my update and delete didn't get saved. Which from my understanding has something to do with cursors being needed to update the contents. However currenty I am stuck with the following error
showAdapter = new ShowsAdapter(this, shows); // the error
Error:(68, 50) error: incompatible types: List cannot be converted to Cursor
private List<Show> shows;
private ShowsAdapter showAdapter;
private RecyclerView recyclerView;
private DataSource datasource;
public static final String INTENT_DETAIL_ROW_NUMBER = "Row number";
public static final String INTENT_DETAIL_REMINDER_TEXT = "Reminder text";
public static final int REQUESTCODE = 2;
public static final String EXTRA_SHOW_ID = "extraShowId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
datasource = new DataSource(this);
datasource.open();
recyclerView = (RecyclerView) findViewById(R.id.main_list);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
//recyclerView.setAdapter(showAdapter);
updateUI();
//registerForContextMenu(recyclerView);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.taskView);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(MainActivity.this, CreateShowActivity.class), 1);
}
});
}
private void updateUI() {
shows = datasource.getAllShows();
if (showAdapter == null) {
showAdapter = new ShowsAdapter(this, shows); // the error
recyclerView.setAdapter(showAdapter);
} else {
showAdapter.notifyDataSetChanged();
}
}
My Adapter:
private List<Show> mShows;
private Context mContext;
private Cursor mShowsCursor;
public void updateList(List<Show> newlist) {
// Set new updated list
mShows.clear();
mShows.addAll(newlist);
notifyDataSetChanged();
}
public ShowsAdapter(Context mContext, Cursor cursor) {
this.mContext = mContext;
this.mShowsCursor = cursor;
}
#Override
public ShowsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(android.R.layout.simple_list_item_1, null);
// Return a new holder instance
ShowsAdapter.ViewHolder viewHolder = new ShowsAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ShowsAdapter.ViewHolder holder, final int position) {
if (mShowsCursor != null && mShowsCursor.moveToPosition(position)) {
holder.textView.setText(mShowsCursor.getString(mShowsCursor.getColumnIndex(MySQLiteHelper.COLUMN_SHOW)));
}
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, EditShowActivity.class);
intent.putExtra(INTENT_DETAIL_ROW_NUMBER, position);
intent.putExtra(INTENT_DETAIL_REMINDER_TEXT, holder.textView.getText());
((MainActivity) mContext).startActivityForResult(intent, REQUESTCODE);
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
mShows.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,mShows.size());
return true;
}
});

Categories