Edit Text values from Recycler View should be updated in Firebase Database - android

I am able to access the marks but want to store them at their respective locations only (meaning every student gets his marks and not someone else's)
This is how my Recycler View looks
Firebase Data Structure
I've got to the point where the data is being collected from a single Edit Text but cannot get its way to the right Student node.
Inside onBindViewHolder method
myViewHolder.btnUpdateMarks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final View v = view;
Result r = new Result();
r.setMarks_scored(myViewHolder.etEnterMarks.getText().toString());
String text = myViewHolder.etEnterMarks.getText().toString();
myViewHolder.updateValue(text,r,v);
}
});
UpdateValue function
public void updateValue(String text, Result r, final View v){
final View view = v;
final Result result = r;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference marksRef = firebaseDatabase.getReference().child("Batches").child("BATCH1");
marksRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot demo : dataSnapshot.getChildren()){
marksRef.child("Results").child("-LfB2Jz7vrbv0vMyYA02").setValue(result);
}
}
The marksRef is being hardcoded which shouldn't be the way.. I am not finding any possible way of getting those child variables inside the adapter class
Anyone with any better soultion to solving the problem please help!
Sorry for the bad communication please mention if anything is missing
-----EDIT---------
I have solved the problem by using a string array inside my activity class and passing it to the constructor of my RecyclerViewAdapter..
The problem is whenever i am typing anything in the edit text of 2nd or 3rd item after clicking the update button the cursor is automatically going to the first item's edittext
This is my adapter class
public class MarksListAdapter extends RecyclerView.Adapter<MarksListAdapter.MyViewHolder> {
Context context;
ArrayList<Result> resultArrayList;
String[] firebaseChildValues = new String[2];
String student_uid;
public MarksListAdapter(Context c, ArrayList<Result> p, String[] child) {
context = c;
resultArrayList = p;
firebaseChildValues = child;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.marks_list, viewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
myViewHolder.tvStudentName.setText(resultArrayList.get(i).getName());
myViewHolder.tvOutOf_List.setText(" / " + resultArrayList.get(i).getTotal_marks());
myViewHolder.etEnterMarks.setText(resultArrayList.get(i).getMarks_scored());
myViewHolder.tvStudentUid.setText(resultArrayList.get(i).getStudent_uid());
myViewHolder.btnUpdateMarks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final View v = view;
student_uid = myViewHolder.tvStudentUid.getText().toString();
Result r = new Result();
r.setMarks_scored(myViewHolder.etEnterMarks.getText().toString());
String text = myViewHolder.etEnterMarks.getText().toString();
myViewHolder.updateValue(text, r, v, firebaseChildValues, student_uid);
}
});
}
#Override
public int getItemCount() {
return resultArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvStudentName, tvOutOf_List, tvStudentUid;
EditText etEnterMarks;
Button btnUpdateMarks;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tvStudentName = (TextView) itemView.findViewById(R.id.tvStudentName);
etEnterMarks = (EditText) itemView.findViewById(R.id.etEnterMarks);
tvOutOf_List = (TextView) itemView.findViewById(R.id.tvOutOf_List);
tvStudentUid = (TextView) itemView.findViewById(R.id.tvStudentUid);
btnUpdateMarks = (Button) itemView.findViewById(R.id.btnUpdateMarks);
}
public void updateValue(String text, Result r, final View v, String[] child, String suid) {
final View view = v;
final Result result = r;
String[] firebaseChildValues = child;
String resultValue = text;
String studentUid = suid;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference marksRef = firebaseDatabase.getReference().child("Batches").child(firebaseChildValues[0]).child(studentUid).child("Results").child(firebaseChildValues[1]);
marksRef.child("marks_scored").setValue(resultValue).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("TAG_MARKS", marksRef.toString());
}
}
});
}
}
}

Remove btnUpdateMarks.setOnClickListener from onBindViewHolder
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
myViewHolder.tvStudentName.setText(resultArrayList.get(i).getName());
myViewHolder.tvOutOf_List.setText(" / " + resultArrayList.get(i).getTotal_marks());
myViewHolder.etEnterMarks.setText(resultArrayList.get(i).getMarks_scored());
myViewHolder.tvStudentUid.setText(resultArrayList.get(i).getStudent_uid());
}
In MyViewHolder Class set btnUpdateMarks.setOnClickListener
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tvStudentName = (TextView) itemView.findViewById(R.id.tvStudentName);
etEnterMarks = (EditText) itemView.findViewById(R.id.etEnterMarks);
tvOutOf_List = (TextView) itemView.findViewById(R.id.tvOutOf_List);
tvStudentUid = (TextView) itemView.findViewById(R.id.tvStudentUid);
btnUpdateMarks = (Button) itemView.findViewById(R.id.btnUpdateMarks);
btnUpdateMarks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
student_uid = tvStudentUid.getText().toString();
String text = etEnterMarks.getText().toString();
Result r = new Result();
r.setMarks_scored(text);
int itemClickedPosition = getLayoutPosition();
//updateValue(text, r, v, firebaseChildValues, student_uid);
//change your updateValue() method accordingly
}
});
}

Related

How do I show info from two different models / adapters in one recyclerview

I have two Models (ModelChat and ModelUsers) and their class adapters (PostsAdapter and AllUsersAdapter).
I want to get and set user info such as name and email from the ModelUser and get and set post information from the ModelPost from Firebase database into the same recyclerview in my HomeActivity.
The codes are as shown below:
PostsAdapter.java
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.MyHolder>{
Context context;
List<ModelPost> postList;
public PostsAdapter(Context context, List<ModelPost> postList) {
this.context = context;
this.postList = postList;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate layout row_post.xml
View view = LayoutInflater.from(context).inflate(R.layout.row_posts, parent, false);
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int position) {
//get data
String userUID = postList.get(position).getUserUID();
String userEmail = postList.get(position).getUserEmail();
String userProfilePic = postList.get(position).getUserProfilePic();
String firstName = postList.get(position).getUserFirstName();
String lastName = postList.get(position).getUserLastName();
String userNickName = postList.get(position).getUserNickName();
String postTimeStamp = postList.get(position).getPostTime();
String userPost = postList.get(position).getUserPost();
//set data
//set data
Glide
.with(context)
.load(userProfilePic)
.apply(RequestOptions.circleCropTransform())
.into(holder.avatarTv);
holder.firstnameTv.setText(firstName);
holder.lastnameTv.setText(lastName);
holder.nicknameTv.setText(userNickName);
}
#Override
public int getItemCount() {
return postList.size();
}
//view holder class
class MyHolder extends RecyclerView.ViewHolder {
//views from row_posts layout
public MyHolder(#NonNull View itemView) {
super(itemView);
//init view
//my views here
}
}
}
AllUsersAdapter.java
public class AllUsersAdapter extends RecyclerView.Adapter<AllUsersAdapter.MyHolder>{
Context context;
List<ModelUser> userList;
//Constructor > Generate
public AllUsersAdapter(Context context, List<ModelUser> userList) {
this.context = context;
this.userList = userList;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//Inflate layout (row_user)
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_all_users, parent, false);
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int position) {
//get data
String userUID = userList.get(position).getUid();
String userProfilePic = userList.get(position).getProfilepic();
String userName = userList.get(position).getFirstname() + " " + userList.get(position).getLastname();
String userNickname = userList.get(position).getNickname();
String userStatus = userList.get(position).getStatus();
//set data
Glide
.with(context)
.load(userProfilePic)
.apply(RequestOptions.circleCropTransform())
.into(holder.mAvatarIv);
holder.mNameTv.setText(userName);
holder.mNicknameTv.setText(userNickname);
holder.mStatusTv.setText(userStatus);
//Handle item click
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Click user from user list to start conversation
*Start Activity by putting UID of receiver
*we will use that UID to identify the user we are gonna chat */
Intent intent = new Intent(context, MessageActivity.class);
intent.putExtra("userUid", userUID);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return userList.size();
}
class MyHolder extends RecyclerView.ViewHolder {
public MyHolder(#NonNull View itemView) {
super(itemView);
//init my views here
}
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
FirebaseAuth firebaseAuth;
RecyclerView recyclerView;
List<ModelPost> postList;
PostsAdapter postsAdapter;
String mUID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
firebaseAuth = FirebaseAuth.getInstance();
//recyclerview and its properties
recyclerView = findViewById(R.id.posts_recyclerview);
//init post list
postList = new ArrayList<>();
loadPosts();
}
private void loadPosts() {
//path of all posts
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
//get all data from this reference
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
postList.clear();
for (DataSnapshot ds: snapshot.getChildren()) {
ModelPost modelPost = ds.getValue(ModelPost.class);
postList.add(modelPost);
//adapter
postsAdapter = new PostsAdapter(HomeActivity.this, postList);
//set adapter to recyclerview
recyclerView.setAdapter(postsAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
//in case of errors
//Toast.makeText(HomeActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Try using ConcatAdapter.
An RecyclerView.Adapter implementation that presents the contents of multiple adapters in sequence. More info
Concatenate adapters sequentially with ConcatAdapter:
https://medium.com/androiddevelopers/merge-adapters-sequentially-with-mergeadapter-294d2942127a
I think this will help
MyAdapter adapter1 = ...;
AnotherAdapter adapter2 = ...;
ConcatAdapter concatenated = new ConcatAdapter(adapter1, adapter2);
recyclerView.setAdapter(concatenated);

How to implement recyclerview ItemClickListener() in Firebase recycler adapter?

I've followed this tutorial at YouTube.
I manage to search the data but now I want to open the details page of selected data on recycler view. How do I get it done? At which part should I implement the onClickListener for recyclerview? I've tried to put onClickListener, intent put extra ... in method OnBindViewHolder and SetDetails, but both of them have problems to recognize my context.
Here is my current code:
private void firebaseIngredientSearch(String searchIngredient) {
Toast.makeText(SearchActivity.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = databaseReference.orderByChild("ingName").startAt(searchIngredient).endAt(searchIngredient + "\uf8ff");
FirebaseRecyclerOptions<Ingredients> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Ingredients>()
.setQuery(firebaseSearchQuery, Ingredients.class)
.build();
FirebaseRecyclerAdapter<Ingredients, SearchActivity.IngredientsViewHolder> firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<Ingredients, SearchActivity.IngredientsViewHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull IngredientsViewHolder holder, int position, #NonNull final Ingredients model) {
holder.setDetails(model.getIngName(), model.getIngStatus(),model.getIngCategory(),model.getIngCategory());
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goDetail = new Intent(, IngredientSearchDetailsActivity.class);
goDetail.putExtra("ingName", model.getIngName());
goDetail.putExtra("ingStatus", model.getIngStatus());
goDetail.putExtra("ingCategory", model.getIngCategory());
goDetail.putExtra("ingDescription", model.getIngDescription());
mActivity.startActivity(goDetail);
}
});
}
#NonNull
#Override
public IngredientsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_searched_ingredient, parent, false);
return new IngredientsViewHolder(view);
}
};
firebaseRecyclerAdapter.startListening();
rvSearchResult.setAdapter(firebaseRecyclerAdapter);
}
////////////////////////////////////////////////////////////////////////////////
public static class IngredientsViewHolder extends RecyclerView.ViewHolder {
View view;
public IngredientsViewHolder(#androidx.annotation.NonNull View itemView) {
super(itemView);
view = itemView;
}
public void setDetails(String ingName, String ingStatus, String ingCategory, String ingDescription) {
TextView i_Name = view.findViewById(R.id.tvName);
TextView i_Status = view.findViewById(R.id.tvStatus);
TextView i_Category = view.findViewById(R.id.tvCategory);
TextView i_Description = view.findViewById(R.id.tvDescription);
ImageView iv_Status = view.findViewById(R.id.searchStatusIv);
i_Name.setText(ingName);
i_Status.setText(ingStatus);
i_Category.setText(ingCategory);
i_Description.setText(ingDescription);
}
}
User holder.view.setOnClickListener to initiate OnClickListener and use holder.view.getContext() instead of mActivity
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goDetail = new Intent(, IngredientSearchDetailsActivity.class);
goDetail.putExtra("ingName", model.getIngName());
goDetail.putExtra("ingStatus", model.getIngStatus());
goDetail.putExtra("ingCategory", model.getIngCategory());
goDetail.putExtra("ingDescription", model.getIngDescription());
holder.view.getContext().startActivity(goDetail);
}
});

how to get position from recyclerview and use it get key for firebase data

I have a recyclerview which upon selection of a radiobutton opens up a alertdialog with options. My problem is getting the position of the selected row(radiobutton) in the recyclerview so I can use it to read from firebase and pass it to the alertdialog.
My onclick method for the radiobutton is used in the RecyclerView.ViewHolder class. And this is where I want to get the position of the selected radiobutton.
RecyclerView onClick
I have read the link above, since I am new to recyclerview and android in general, the solutions in the above link confuse me, its really a headache, tried most of their solution and still unable to find a solution to mine
Main Activity
public class Review2 extends AppCompatActivity {
private TextView impres, impress1, impress2,impress3,impress4,impress5;
private RecyclerView patient_drug_list;
private FirebaseAuth mAuth;
private DatabaseReference mDrugList, mNameDiag, mName;
private TextView desker, name, dater;
public String drug, dosing;
FirebaseRecyclerAdapter<Drugs, DrugsViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review2);
///Firebase Authentication and related properties
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
String uId = mUser.getUid();/// id or users
desker = findViewById(R.id.desk);
String user_id = getIntent().getStringExtra(Review1.REVIEW_ID);///retrieve value from activity
///Toast.makeText(this, user_id, Toast.LENGTH_LONG).show();///verify if value is gotten
Query query = FirebaseDatabase.getInstance().getReference().child("Drugs").child(uId).child(user_id);
query.keepSynced(true);
patient_drug_list = (RecyclerView) findViewById(R.id.recycler2); ////Recycler view from xml
patient_drug_list.setLayoutManager(new LinearLayoutManager(this));
patient_drug_list.setHasFixedSize(true);
///////////////////////////Assign Items
impres = findViewById(R.id.diagnose1);
impress1 = findViewById(R.id.diagnose2);
impress2 = findViewById(R.id.diagnose3);
impress3 = findViewById(R.id.diagnose4);
impress4 = findViewById(R.id.diagnose5);
impress5 = findViewById(R.id.diagnose6);
name = findViewById(R.id.RName);
dater = findViewById(R.id.RDate);
/////////////Reading firebase data
mNameDiag = FirebaseDatabase.getInstance().getReference().child("Diagnosis").child(uId).child(user_id);
mNameDiag.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String diagnosis1 = dataSnapshot.child("diagnosis1").getValue().toString();
String diagnosis2 = dataSnapshot.child("diagnosis2").getValue().toString();
String diagnosis3 = dataSnapshot.child("diagnosis3").getValue().toString();
String diagnosis4 = dataSnapshot.child("diagnosis4").getValue().toString();
String diagnosis5 = dataSnapshot.child("diagnosis5").getValue().toString();
impres.setText(diagnosis1);
impress1.setText(diagnosis2);
impress2.setText(diagnosis3);
impress3.setText(diagnosis4);
impress4.setText(diagnosis5);
impress5.setText(diagnosis5);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
/////////////////////////////////////////////////////////////////
mName = FirebaseDatabase.getInstance().getReference().child("Patients").child(uId).child(user_id);
mName.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String namer = dataSnapshot.child("name").getValue().toString();
String dater1 = dataSnapshot.child("date").getValue().toString();
name.setText(namer);
dater.setText(dater1);
adapter.startListening();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
////Firebase Adapter and related properties
FirebaseRecyclerOptions<Drugs> options = new FirebaseRecyclerOptions.Builder<Drugs>()
.setQuery(query, Drugs.class).build();
adapter = new FirebaseRecyclerAdapter<Drugs, DrugsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull DrugsViewHolder holder, final int position, #NonNull Drugs model) {
holder.setDiag1(model.getBrand());
holder.setDiag2(model.getGeneric());
holder.setDiag3(model.getDose());
holder.setDiag4(model.getFrequency1(), model.getFrequency2(), model.getDuration());
}
#NonNull
#Override
public DrugsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
////Recycler view item
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.drug_display_list,viewGroup,false);///
return new DrugsViewHolder(view);
}
};
patient_drug_list.setLayoutManager(new LinearLayoutManager(this));
patient_drug_list.setAdapter(adapter);//// setting adapter
adapter.notifyDataSetChanged();
adapter.startListening();
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
adapter.notifyDataSetChanged();
}
////////////////click for new option activities
//This is a switch for the adio button options that appear after the above radiobutton
public void clickers(View view) {
switch (view.getId()){
case R.id.drug_needed:
startActivity(new Intent(getApplicationContext(),Drug_needed.class));
break;
case R.id.wrong_drug:
Toast.makeText(Review2.this, "2nd", Toast.LENGTH_SHORT).show();
break;
case R.id.dose_related:
startActivity(new Intent(getApplicationContext(),Dose.class));
break;
case R.id.adverse_reaction:
startActivity(new Intent(getApplicationContext(),ADR.class));
break;
case R.id.food_interaction:
Toast.makeText(this, "yet to do", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(Review2.this, "nothing to see", Toast.LENGTH_SHORT).show();
break;
}
}
////////////////View Holder
private class DrugsViewHolder extends RecyclerView.ViewHolder{
View mView;
DrugsViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
final RadioButton radioButton = mView.findViewById(R.id.not_appropriate);
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position1 = getAdapterPosition();
AlertDialog.Builder myDialog = new AlertDialog.Builder(Review2.this);
LayoutInflater inflater = LayoutInflater.from(Review2.this);
View myview = inflater.inflate(R.layout.adr_options, null);
myDialog.setView(myview);
myDialog.show();
}
});
}
void setDiag1(String diag1){
TextView postdiag1 = mView.findViewById(R.id.brand);
postdiag1.setText(diag1);
}
void setDiag2(String diag2){
TextView postdiag2 = mView.findViewById(R.id.generic);
postdiag2.setText(diag2);
postdiag2.setTextSize(12);
}
public void setDiag3(String diag3){
TextView postdiag3 = mView.findViewById(R.id.dose);
postdiag3.setText("Dose:" + diag3);
}
public void setDiag4(String diag4, String diag5, String diag6){
TextView postdiag4 = mView.findViewById(R.id.frequency);
postdiag4.setText("Frequency:" + diag4 + " tab " + diag5+"x" + "daily for "+diag6 + "days");
}
}
}
So to keep it simple, I just want to be able to get the position of the recyclerview row with the selected radiobutton from the RecyclerView.ViewHolder class .Any suggestions, ideas or examples would be appreciated.
How I see it:
You can create own adapter with inner ViewHolder class. So you can change fields of adapter from ViewHolder;
Create selectedRowPosition or selectedRowsPositions field inside adapter;
Change selectedRowPosition when state of radio button is changed;
Read selectedRowPosition field of adapter when you need it.
Update
I've created repository when you can see strategy described above. Most important class is adapter:
public class RadioButtonsAdapter extends RecyclerView.Adapter<RadioButtonsAdapter.RadioViewHolder> {
// Field when we store position of last clicked item
private int lastClickedItemPosition;
#NonNull
#Override
public RadioViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RadioButton button = new RadioButton(parent.getContext());
return new RadioViewHolder(button);
}
#Override
public void onBindViewHolder(#NonNull RadioViewHolder holder, int position) {
holder.radioButton.setText("It is button #" + position);
}
#Override
public int getItemCount() {
return 30;
}
// Use this method to get lastClickedItemPosition
public int getLastClickedItemPosition() {
return lastClickedItemPosition;
}
// This is inner class. From this class you can change 'lastClickedItemPosition' field of adapter
class RadioViewHolder extends RecyclerView.ViewHolder {
private RadioButton radioButton;
public RadioViewHolder(#NonNull View itemView) {
super(itemView);
radioButton = (RadioButton) itemView;
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lastClickedItemPosition = getAdapterPosition();
}
});
}
}
}
You can call adapter.getLastClickedItemPosition() to get position of last clicked item. Full code of MainActivty is on github. MainActivity is written on Kotlin but don't worry, it easy to understand.
Attention!!!
I don't recommend you to use RadioButton inside RecyclerView. The common usage of RadioButton is inside RadioGroup. Check this link to read more details about usage of RadioButton.

What do i put in onBindViewHolder to bind my models and populate my RecyclerView?

Right now I'm just trying to use Firebase UI 3.1.1 to populate a recycler view. All the tutorials im seeing are outdated, and the ones that are dated are incomplete. This is what i have so far...
private void setUpFirebaseAdapter() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(Constants.LOBBIES);
Query query = reference;
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
FirebaseRecyclerOptions lobbyOptions = new FirebaseRecyclerOptions.Builder<Lobby>().setQuery(query, Lobby.class).build();
mLobbyAdapter = new FirebaseRecyclerAdapter<Lobby, LobbyViewHolder>(lobbyOptions) {
#Override
protected void onBindViewHolder(#NonNull LobbyViewHolder holder, int position, #NonNull Lobby model) {
holder.
}
#Override
public LobbyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
};
}
what do i put in holder so i can complete the recycler view? Thanks!
EDIT. Here's my View holder class too
public class LobbyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View mView;
Context mContext;
public LobbyViewHolder(View itemView) {
super(itemView);
mView = itemView;
mContext = itemView.getContext();
itemView.setOnClickListener(this);
}
public void bindLobby(Lobby lobby) {
TextView nameTextView = (TextView) mView.findViewById(R.id.lobby_name_text);
TextView locationTextView = (TextView) mView.findViewById(R.id.lobby_location_text);
TextView sizeTextView = (TextView) mView.findViewById(R.id.lobby_size_text);
TextView priceTextView = (TextView) mView.findViewById(R.id.lobby_price_text);
TextView dateTextView = (TextView) mView.findViewById(R.id.lobby_date_text);
nameTextView.setText(lobby.getOwner());
locationTextView.setText(lobby.getLocation());
sizeTextView.setText(lobby.getTotalMembers());
priceTextView.setText("Php " + lobby.getCost());
dateTextView.setText(lobby.getDateText());
}
#Override
public void onClick(View v) {
final ArrayList<Lobby> lobbies = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(Constants.LOBBIES);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
lobbies.add(snapshot.getValue(Lobby.class));
}
int itemPosition = getLayoutPosition();
Intent intent = new Intent(mContext, LobbyDetailActivity.class);
intent.putExtra("position", itemPosition + "");
intent.putExtra("lobbies", Parcels.wrap(lobbies));
mContext.startActivity(intent);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
From what I'm seeing you're not inflating the layout view (onCreateViewHolder) too, Do it like this:
private void setUpFirebaseAdapter() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(Constants.LOBBIES);
Query query = reference;
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
FirebaseRecyclerOptions lobbyOptions = new FirebaseRecyclerOptions.Builder<Lobby>().setQuery(query, Lobby.class).build();
mLobbyAdapter = new FirebaseRecyclerAdapter<Lobby, LobbyViewHolder>(lobbyOptions) {
#Override
protected void onBindViewHolder(#NonNull LobbyViewHolder holder, int position, #NonNull Lobby model) {
holder.bindLobby(model);
//here you associate the holder views with the model attributes
}
#Override
public LobbyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_layout_file, parent, false);
return new LobbyViewHolder(view);
}
};
}

SQLite Database - List all data from database with RecyclerView/adapter

i want to list all my stored data on database and show it on using a recycler view/adapter. Can anyone help me about this.
-i have a class of getter and setter(PWClass)
Here are some of my codes:
This is the time i am storing some data on class and add it on list but it is only a sample.
PWClass pwc = new PWClass("Facebook", "Action & Adventure", "2015");
pwList.add(pwc);
pwc = new PWClass("Instagram", "Action & Adventure", "2015");
pwList.add(pwc);
mAdapter.notifyDataSetChanged();
My problem is how can i combine the code above and calling a query on database to display datas like:
//i declare on top
private List<PWClass> pwList = new ArrayList<>();
private RecyclerView recyclerView;
private PWAdapter mAdapter;
Database controller;
//and from a method below
pwList.add(controller.add_pw());//adding on list array by calling my db method
Should i use some for/while loops/arrays? I am thinking the code above but i know its wrong. Do you get my point?
Please help so i can understand more, i appreciate your suggestions thanks!
read this post, you will get clear idea on Sqlite database.
check this out
public List<userData> getAlluser() {
List<userData> usersdetail = new ArrayList<>();
curser = dbs.query("data_table", null, null, null, null, null, null);
try {
if (curser.moveToFirst()) {
do {
userData muser = new userData();
muser.appname = curser.getString(curser.getColumnIndex("appname"));
muser.user = curser.getString(curser.getColumnIndex("email"));
muser.passwordss = curser.getString(curser.getColumnIndex("password"));
usersdetail.add(muser);
} while (curser.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
return usersdetail;
}
public class RecyclerViewAdopterMy extends RecyclerView.Adapter<RecyclerViewAdopterMy.MyViewHolder> implements View.OnClickListener {
List<userData> user = new ArrayList<>();
Context context;
public RecyclerViewAdopterMy(List<userData> user, Context context) {
this.user = user;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, null);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.appR.setText(user.get(position).appname);
holder.nameR.setText(user.get(position).user);
holder.passR.setText(user.get(position).passwordss);
holder.cardR.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(view.getRootView().getContext());
alertbox.setMessage("Do you want delete this item");
alertbox.setTitle("Delete");
alertbox.setIcon(R.drawable.delete);
alertbox.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
int pos = holder.getAdapterPosition();
user.remove(user.get(position));
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount());
notifyItemChanged(position);
}
});
alertbox.show();
return true;
}
});
}
#Override
public int getItemCount() {
return user.size();
}
#Override
public void onClick(View view) {
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView appR;
private final TextView nameR;
private final TextView passR;
private final CardView cardR;
public MyViewHolder(View view) {
super(view);
appR = (TextView) view.findViewById(R.id.Appstore);
nameR = (TextView) view.findViewById(R.id.userStore);
passR = (TextView) view.findViewById(R.id.passstore);
cardR = (CardView) view.findViewById(R.id.card);
}
}
}

Categories

Resources