I have a database where my data looks like this.
I have used Firebase Recycler Adapter to the info for S1, S2 and so on, to represent that data in a recycler view. However the data is not showing only in my application. The application is for a teacher to see whether the student is present or not by retrieving data from Firebase.
AttendaceFrag.java
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class AttendanceFrag extends Fragment {
RecyclerView recyclerView;
DatabaseReference databaseReference;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_attendance_frag, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
databaseReference = FirebaseDatabase.getInstance().getReference().child("Student");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
Toast.makeText(getContext(), "Data to show", Toast.LENGTH_LONG).show();
startShowing();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return v;
}
private void startShowing() {
FirebaseRecyclerAdapter<Student, AttendanceFrag.RequestViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Student, AttendanceFrag.RequestViewHolder>(
Student.class,
R.layout.custom_row,
AttendanceFrag.RequestViewHolder.class,
databaseReference
) {
#Override
protected void populateViewHolder(AttendanceFrag.RequestViewHolder viewHolder, Student model, int position) {
viewHolder.setName(model.getName());
viewHolder.setAp(model.getAp());
viewHolder.setRegno(model.getRegno());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class RequestViewHolder extends RecyclerView.ViewHolder {
View mView;
public RequestViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView stname = (TextView) mView.findViewById(R.id.st_name);
stname.setText(name);
}
public void setRegno(String regno) {
TextView stregno = (TextView) mView.findViewById(R.id.st_regno);
stregno.setText(regno);
}
public void setAp(String ap) {
TextView stap = (TextView) mView.findViewById(R.id.st_ap);
stap.setText(ap);
}
}
}
Student.java
public class Student {
private String name, regno,ap;
public Student(String name, String regno, String ap) {
this.name = name;
this.regno = regno;
this.ap = ap;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegno() {
return regno;
}
public void setRegno(String regno) {
this.regno = regno;
}
public String getAp() {
return ap;
}
public void setAp(String ap) {
this.ap = ap;
}
}
activity_attendance_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:padding="3dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.xxx.AttendanceFrag">
<TableLayout
android:id="#+id/table_lay"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow
android:id="#+id/firstrow"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:background="#drawable/r1"
android:text="Sr. No."
android:id="#+id/srnohead"
android:textAlignment="center"
android:padding="5dp"
android:textColor="#color/colorPrimaryDark"
/>
<TextView
android:padding="5dp"
android:textAlignment="center"
android:background="#drawable/r1"
android:text="Reg. Number"
android:layout_width="135dp"
android:id="#+id/regNohead"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:padding="5dp"
android:background="#drawable/r1"
android:text="Name"
android:textAlignment="center"
android:layout_height="wrap_content"
android:layout_width="120dp"
android:id="#+id/namehead"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:padding="5dp"
android:background="#drawable/r1"
android:text="P/A"
android:layout_height="wrap_content"
android:id="#+id/attnhead"
android:textColor="#color/colorPrimaryDark"/>
</TableRow>
</TableLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/table_lay"
android:layout_alignParentStart="true"
android:layout_marginTop="33dp" />
</RelativeLayout>
custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:padding="3dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="#drawable/r1"
android:text="Sr. No."
android:id="#+id/st_sr"
android:textAlignment="center"
android:padding="5dp"
android:textColor="#color/colorPrimaryDark"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="135dp"
android:padding="5dp"
android:textAlignment="center"
android:background="#drawable/r1"
android:text="Reg. Number"
android:id="#+id/st_regno"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:padding="5dp"
android:background="#drawable/r1"
android:text="Name"
android:textAlignment="center"
android:layout_height="wrap_content"
android:layout_width="120dp"
android:id="#+id/st_name"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:layout_width="wrap_content"
android:padding="5dp"
android:background="#drawable/r1"
android:text="P/A"
android:layout_height="wrap_content"
android:id="#+id/st_ap"
android:textColor="#color/colorPrimaryDark"/>
</LinearLayout>
put this in your App level gradle : implementation 'com.firebaseui:firebase-ui-database:3.2.1'
In your onStart method put this :
#Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Blog")
.limitToLast(50);
FirebaseRecyclerOptions<BlogModel> options =
new FirebaseRecyclerOptions.Builder<BlogModel>()
.setQuery(query, BlogModel.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<BlogModel, BlogViewHolder>(options) {
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_blog, parent, false);
return new BlogViewHolder(view);
}
#Override
protected void onBindViewHolder(BlogViewHolder holder, int position, BlogModel model) {
holder.setTitleBlog(model.getTitle());
holder.setTitleDesc(model.getDescription());
holder.setImage(getApplicationContext(), model.getImage_url());
}
};
adapter.startListening();
mRecycler.setAdapter(adapter);
}
in your BlogViewHolder put this :
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View view;
public BlogViewHolder(View itemView) {
super(itemView);
view = itemView;
}
public void setTitleBlog(String title) {
TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
tvTitle.setText(title);
}
public void setTitleDesc(String desc) {
TextView tvDesc = (TextView) view.findViewById(R.id.tv_desc);
tvDesc.setText(desc);
}
public void setImage(Context context, String url) {
ImageButton ib = (ImageButton) view.findViewById(R.id.ib_blog);
Picasso.with(context).load(url).into(ib);
}
}
And your are all set to go :)
Your database reference pointing wrong node you can use it like this:
FirebaseDatabase.getInstance().getReferenceFromUrl("https://facapp-bee2.firebaseio.com/");
Then .child("Faculty/Student") and recylerview don't use addValueListener. Here you can find how to use recycler view in firebase
Related
I am unable to display the image (only) in RecyclerView stored in Firebase Storage, while I'm displaying the other text data in the recyclerView.
I browse through a lot of questions but i didn't find the answer for me .
hint: all roles for Realtime Database , Firebase Storage is set either to [true or test mode]
hint : below is the link for out put image :
https://i.stack.imgur.com/dagbA.jpg
data model
import com.google.firebase.database.Exclude;
public class House {
#Exclude
private String key;
//owner name
private String name ;
//location
private String Location;
//image
private String imageUrl;
/*all start with [RealState] (realTimeDatabase/storage)*/
/*
* [RealStateData] - database
* [RealStatePictures] - storage
* */
public House() {
//required
}
public House(String name, String location, String imageUrl) {
if (name.trim().equals("") || name.isEmpty()){
name = "realState company";
}
this.name = name;
Location = location;
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
#Exclude
public String getKey() {
return key;
}
#Exclude
public void setKey(String key) {
this.key = key;
}
}
Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import com.techmarinar.royalhomes.data.House;
import java.util.List;
public class HouseAdapter extends RecyclerView.Adapter<HouseAdapter.HouseHolder> {
private static final String TAG = "HouseAdapter";
private Context mContext;
private List<House> houseList;
public HouseAdapter(Context mContext, List<House> houseList) {
this.mContext = mContext;
this.houseList = houseList;
}
public void setUploads(List<House> uploads) {
this.houseList = uploads;
this.notifyDataSetChanged();
}
#NonNull
#Override
public HouseHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(mContext)
.inflate(R.layout.list_item,parent,false);
return new HouseHolder(v);
}
#Override
public void onBindViewHolder(#NonNull HouseHolder holder, int position) {
//house object
House house = houseList.get(position);
holder.name.setText(house.getName());
holder.location.setText(house.getLocation());
// holder.image.setImageURI(Uri .parse(house.getImageUrl());
String imageUrl = house.getImageUrl();
Glide.with(mContext)
.load(imageUrl)
.placeholder(R.drawable.ic_baseline_add_business_24)
.centerCrop()
.into(holder.image);
}
#Override
public int getItemCount() {
return houseList.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class HouseHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView name;
private TextView location ;
public HouseHolder(#NonNull View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.xHouseImage);
name = (TextView) itemView.findViewById(R.id.xHouseName);
location = (TextView) itemView.findViewById(R.id.xHouseLocation);
}
}
}
MainActicity -- recyclerclass
package com.techmarinar.royalhomes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.techmarinar.royalhomes.data.House;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements MenuItem.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
//widget
private RecyclerView mRecycler;
private ProgressBar mProgress;
//firebase Element
private StorageReference storageReference;
private DatabaseReference databaseReference;
//Adapters var
private List<House> houseList;
private HouseAdapter mAdapter;
private ValueEventListener getFirebaseData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set Widget
setupUIWidget();
//init firebase
initiateFireBaseElement();
//set recyclerView
setupRecyclerView();
//get data from fire(storage/fireDataBase);
getHousesDataFromFireBase();
//setup Item Touch Helper
setupItemTouchHelper(mRecycler , mAdapter);
}
private void setupUIWidget() {
setTitle("home");
//widget
mProgress = (ProgressBar) findViewById(R.id.progress_circular);
mRecycler = (RecyclerView) findViewById(R.id.recycler);
FloatingActionButton mActionButton = (FloatingActionButton) findViewById(R.id.floatingBtn);
//ActionButton
mActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this, "wow", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this , EditHouse.class));
}
});
}
private void initiateFireBaseElement() {
//fireBase reference
databaseReference = FirebaseDatabase.getInstance().getReference("RealStateData");
storageReference= FirebaseStorage.getInstance().getReference("RealStatePictures") ;
}
private void setupRecyclerView() {
Log.d(TAG, "setupRecyclerView: ");
houseList = new ArrayList<>();
mRecycler.setLayoutManager(new LinearLayoutManager(this));
mRecycler.setHasFixedSize(true);
//mRecycler.setHasStableIds(true);
//init adapter
mAdapter = new HouseAdapter(MainActivity.this,houseList);
//set adapter to the recyclerView
mRecycler.setAdapter(mAdapter);
}
private void getHousesDataFromFireBase() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
houseList.clear();
for (DataSnapshot data : snapshot.getChildren()) {
//init house object
House houseValues = data.getValue(House.class);
// houseValues.setKey(data.getKey());
//fill the list
houseList.add(houseValues);
}
//notify the adapter
mAdapter.setUploads(houseList);
//mAdapter.notifyDataSetChanged();
//hide the progressBar
mProgress.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: " + error.getMessage());
Toast.makeText(MainActivity.this, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
//hide progressbar
mProgress.setVisibility(View.INVISIBLE);
}
});
}
private void setupItemTouchHelper(RecyclerView mRecycler, HouseAdapter mAdapter) {
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
}).attachToRecyclerView(mRecycler);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu
MenuItem addNewHouse , deleteHouse , updateHouse;
addNewHouse= menu.add(0,1,1,"add house");
addNewHouse.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
addNewHouse.setIcon(R.drawable.ic_baseline_supervised_user_circle_24);
updateHouse= menu.add(0,2,2,"update house");
deleteHouse= menu.add(0,3,3,"delete house");
addNewHouse.setOnMenuItemClickListener(this);
updateHouse.setOnMenuItemClickListener(this);
deleteHouse.setOnMenuItemClickListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case 1:
Toast.makeText(this, "new house", Toast.LENGTH_SHORT).show();
return true;
case 2:
Toast.makeText(this, "update house data", Toast.LENGTH_SHORT).show();
return true;
case 3:
Toast.makeText(this, "delete house data", Toast.LENGTH_SHORT).show();
return true;
default:return false;
}
}
}
here is xml files
List item:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="2dp"
app:cardBackgroundColor="#color/purple_200"
app:cardElevation="12dp"
app:cardCornerRadius="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp">
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#color/purple_200"/>
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"/>
<ImageView
android:id="#+id/xHouseImage"
android:layout_width="match_parent"
android:layout_height="220dp"
android:adjustViewBounds="true" />
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"/>
<TextView
android:id="#+id/xHouseLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="house Location"
android:layout_margin="4dp"
android:layout_marginStart="6dp"
android:fontFamily="sans-serif-light"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"
android:textColor="#color/black"
android:textSize="33sp"/>
<TextView
android:id="#+id/xHouseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="house owner name"
android:layout_margin="4dp"
android:layout_marginStart="8dp"
android:fontFamily="sans-serif-light"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/black"
android:textSize="16sp"
android:gravity="top|center_vertical" />
</LinearLayout>
</androidx.cardview.widget.CardView>
recycler
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:layout_margin="8dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_goneMarginBottom="8dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.029" />
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.446"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.406" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_baseline_home_work_24"
android:backgroundTint="#color/white"
android:foregroundGravity="bottom|right"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.945" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try this applyDefaultRequestOptions Method for Center crop of the image
Glide.with(mContext)
.applyDefaultRequestOptions(RequestOptions().centerCrop())
.load(imageUrl)
.placeholder(R.drawable.ic_baseline_add_business_24)
.into(target!!)
the problem was in Manifest.xml security issuess.
solution :
adding
android:usesCleartextTraffic="true"
to the application section
I am using firebase ui to load data from firebase database to recycler view but the data is not showing up inside the recycler view.
This is my fragment
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
import com.infinity.houseestimatorandmodeler.R;
import com.infinity.houseestimatorandmodeler.databinding.FragmentBuildersBinding;
public class BuilderFragment extends Fragment {
private BuilderAdapter adapter;
public BuilderFragment() {
// Required empty public constructor
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
FragmentBuildersBinding databinding= DataBindingUtil.inflate(inflater, R.layout.fragment_builders, container, false);
FirebaseRecyclerOptions<buildersModel> options =
new FirebaseRecyclerOptions.Builder<buildersModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("builders"), buildersModel.class)
.build();
adapter = new BuilderAdapter(options);
databinding.buildersRecyclerView.setAdapter(adapter);
return databinding.getRoot();
}
}`
this is my adapter class that is adapting the data for showing in the recycler view
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.infinity.houseestimatorandmodeler.R;
public class BuilderAdapter extends FirebaseRecyclerAdapter<buildersModel, BuilderAdapter.BuilderViewHolder> {
public BuilderAdapter(#NonNull FirebaseRecyclerOptions<buildersModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull BuilderViewHolder holder, int i, #NonNull buildersModel builder) {
holder.name.setText(builder.getName());
holder.builderClass.setText(builder.getBuilderClass());
holder.address.setText(builder.getAddress());
}
#NonNull
#Override
public BuilderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.builders_card, parent, false);
return new BuilderViewHolder(view);
}
class BuilderViewHolder extends RecyclerView.ViewHolder{
TextView name, builderClass, address;
public BuilderViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.nameofbuilder);
builderClass = itemView.findViewById(R.id.classOfBuilder);
address = itemView.findViewById(R.id.address);
}
}
}
this is my model class for data coming from firebase `
class buildersModel
{
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBuilderClass() {
return builderClass;
}
public void setBuilderClass(String builderClass) {
this.builderClass = builderClass;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public buildersModel(String address, String builderClass, String name) {
this.address = address;
this.builderClass = builderClass;
this.name = name;
}
String address;
String builderClass;
String name;}
this is my firebase database
card view for individual element in recycler view
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/rounded_cards"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<androidx.appcompat.widget.AppCompatImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_margin="20dp"
android:src="#drawable/ic_builder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/rounded_cards">
<TextView
android:id="#+id/nameofbuilder"
android:layout_marginTop="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/baloo"
android:textSize="20dp"
android:padding="2dp"
android:text="Abdul Shakoor"/>
<TextView
android:id="#+id/classOfBuilder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textSize="15sp"
android:textColor="#342C2C"
android:padding="2dp"
android:text="Location Islambad"/>
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#342C2C"
android:padding="2dp"
android:text="Address : I10 Islamabad near Rahimia mosque"/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
recycler view layout
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<data>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:src="#drawable/ic_builders"
android:background="#75CDDC"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/buildersRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
</LinearLayout>
You didn't set the RecyclerView LayoutManger, you can either set it in you layout
<androidx.recyclerview.widget.RecyclerView
....
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
Or in the fragment
databinding.buildersRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
I am using firestore recyclerview, but the items is not displayed on the app. I don't know what the problem is. I used is t before in other projects but still i don't get the mistake I made.
Display Fragment:
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import butterknife.BindView;
import butterknife.ButterKnife;
public class HospitalFragment extends Fragment {
#BindView(R.id.hospitalList)
RecyclerView hospitalList;
CollectionReference medcenters;
FirebaseFirestore ref;
HospitalAdapter hospitalAdapter;
private String TAG="TAG";
public HospitalFragment() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_hospital, container, false);
ButterKnife.bind(this,view);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.e(TAG, "onViewCreated: "+hospitalList);
rvSetUp();
dbSetup();
}
private void dbSetup() {
ref=FirebaseFirestore.getInstance();
medcenters=ref.collection("MedicalCenters");
Query query=medcenters.orderBy("name");
FirestoreRecyclerOptions<RVCell> options=new FirestoreRecyclerOptions.Builder<RVCell>()
.setQuery(query,RVCell.class)
.build();
hospitalAdapter=new HospitalAdapter(options,getContext());
hospitalList.setAdapter(hospitalAdapter);
}
private void rvSetUp() {
hospitalList.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getContext());
hospitalList.setLayoutManager(layoutManager);
}
#Override
public void onStart() {
super.onStart();
hospitalAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
hospitalAdapter.stopListening();
}
}
Adapter. This is the adapter which extends recyclerview Adapter :
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
public class HospitalAdapter extends FirestoreRecyclerAdapter<RVCell,HospitalAdapter.ViewHolder> {
Context context;
public HospitalAdapter(#NonNull FirestoreRecyclerOptions<RVCell> options, Context context){
super(options);
this.context=context;
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull RVCell model)
{
holder.location.setText(model.getLocation());
holder.title.setText(model.getMCName());
holder.phone.setText(model.getPhno());
holder.time.setText(model.getTime());
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.rv_cell, parent, false);
return new ViewHolder(v);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title,location,time,phone;
public ViewHolder(#NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title);
location=itemView.findViewById(R.id.location);
time=itemView.findViewById(R.id.time);
phone=itemView.findViewById(R.id.phno);
}
}
}
Cell. This is the POJO class :
public class RVCell {
String MCName,location,time,phno,picurl,locurl;
public String getMCName() {
return MCName;
}
public void setMCName(String MCName) {
this.MCName = MCName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getPhno() {
return phno;
}
public void setPhno(String phno) {
this.phno = phno;
}
public String getPicurl() {
return picurl;
}
public void setPicurl(String picurl) {
this.picurl = picurl;
}
public String getLocurl() {
return locurl;
}
public void setLocurl(String locurl) {
this.locurl = locurl;
}
}
Main Layout. RecyclerView Layout :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HospitalFragment">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/hospitalList"/>
</FrameLayout>
Cell layout. This is the layout used to diplay the items in the recycler view:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp">
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Location"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/container"
android:background="#color/card_bg_color" />
<RelativeLayout
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:background="#drawable/card_bg"
android:paddingBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_alignStart="#+id/title"
android:layout_alignLeft="#id/title"
android:layout_marginTop="8dp"
android:layout_marginRight="16dp"
android:lineSpacingExtra="8dp"
android:text="Location:"
android:textColor="#color/content_text_color" />
<TextView
android:id="#+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/location"
android:layout_alignStart="#+id/location"
android:layout_alignLeft="#id/location"
android:layout_marginTop="8dp"
android:layout_marginRight="16dp"
android:lineSpacingExtra="8dp"
android:text="Time:"
android:textColor="#color/content_text_color" />
<TextView
android:id="#+id/phno"
android:layout_width="333dp"
android:layout_height="wrap_content"
android:layout_below="#id/location"
android:layout_alignStart="#+id/time"
android:layout_alignLeft="#id/time"
android:layout_marginStart="-2dp"
android:layout_marginLeft="-2dp"
android:layout_marginTop="34dp"
android:layout_marginRight="16dp"
android:lineSpacingExtra="8dp"
android:text="Phone:"
android:textColor="#color/content_text_color" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="40dp"
android:layout_marginLeft="40dp"
android:layout_marginTop="20dp"
android:text="Simple Title Text "
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
</RelativeLayout>
<ImageView
android:id="#+id/img_user"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toStartOf="#+id/container"
app:layout_constraintStart_toStartOf="#+id/container"
app:layout_constraintTop_toTopOf="#+id/container"
app:srcCompat="#mipmap/ic_launcher" />
</androidx.constraintlayout.widget.ConstraintLayout>
This the code. I searched a lot I did not find any mistakes. I also used the listeners of the recycler adapter. If any body can help it would be nice.
Which information has your TAG?
It has to have Name of your Activity, try this:
private static final String TAG = „HospitalFragment“;
I am slightly new to Firebase implementation, and would appreciate any help in the display of my Firebase data in my Android application. There are no specifics in "what data" should be displayed, I am simply attempting to populate the entire database into the application. There are also NOT specific user auth's, the database is shared by all users for the sake of this application.
Here is my Cart.java (Where I would like the data to populate)
package edu.phoenix.mbl402.week2apptt2163;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class sunglass1 extends AppCompatActivity {
private FirebaseAuth mAuth;
private String TAG;
int minteger = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sunglass2);
mAuth = FirebaseAuth.getInstance();
Button button = (Button) findViewById(R.id.addcart);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Octagon Glasses");
myRef.setValue("$64");
Toast.makeText(getBaseContext(), "Added to Cart", Toast.LENGTH_SHORT).show();
}
});
Button button2 = (Button) findViewById(R.id.viewcart);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCart();
}
});
}
public void openCart() {
Intent intent = new Intent(this, cart.class);
startActivity(intent);
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
}}
Here is the cart.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/activity_main"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</RelativeLayout>
Here is my cartadapter.java:
package edu.phoenix.mbl402.week2apptt2163;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class cartadapter extends RecyclerView.Adapter<cartadapter.MyViewHolder> {
private List<cartitems> cartList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, price;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
price = (TextView) view.findViewById(R.id.price);
}
}
public cartadapter(List<cartitems> moviesList) {
this.cartList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cart_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
cartitems items = cartList.get(position);
holder.title.setText(items.getTitle());
holder.price.setText(items.getPrice());
}
#Override
public int getItemCount() {
return cartList.size();
}
}
And of course, cartitems.java:
package edu.phoenix.mbl402.week2apptt2163;
public class cartitems {
private String title, price;
public cartitems() {
}
public cartitems(String title, String price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getPrice() {
return price;
}
public void setPrice(String year) {
this.price = price;
}
}
Here is the cart_list_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:paddingBottom="#dimen/row_padding_vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/row_padding_vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textColor="#color/title"
android:textSize="40dp"
android:text="Your Cart"
android:gravity="center"
android:textStyle="bold" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:id="#+id/price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title" />
</RelativeLayout>
Thank you for absolutely any help,
if you don't use authentication and no error(or Exception) comes then i think you must set auth == null in firebase console database rule part.and if you also done it then check variable name of the class cartitems should same as firebase variable.
This class adds all the users from the firebase database to the recyclerview. I want to add name and email addresses of the selected checkboxes in the recyclerview and then add them to a list
package com.tml.sharethem.demo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class AddMembers extends AppCompatActivity {
TextView txtGroup;
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_members);
String data = getIntent().getExtras().getString("group_name1");
txtGroup= (TextView) findViewById(R.id.txtGroup);
txtGroup.setText("Select Members for "+data+"Group");
mSearchField= (EditText) findViewById(R.id.search_field);
mSearchBtn= (ImageButton) findViewById(R.id.search_btn);
mResultList= (RecyclerView) findViewById(R.id.result__list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mUserDatabase= FirebaseDatabase.getInstance().getReference("Users");
FirebaseRecyclerAdapter<Users,UsersViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Users, UsersViewHolder>(Users.class
,R.layout.list_layout,
UsersViewHolder.class,
mUserDatabase) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.setDetails(model.getName(),model.getEmail());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText=mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(AddMembers.this,"Search Started",Toast.LENGTH_LONG).show();
Query firebaseSearchQuery=mUserDatabase.orderByChild("name").startAt(searchText).endAt(searchText+"\uf8ff");
FirebaseRecyclerAdapter<Users,UsersViewHolder> firebaseRecyclerAdapter1=new FirebaseRecyclerAdapter<Users, UsersViewHolder>(Users.class
,R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.setDetails(model.getName(),model.getEmail());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter1);
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView=itemView;
}
TextView user_name;
TextView user_email;
CheckBox checkBox;
public void setDetails(String userName,String userEmail)
{
user_name=(TextView)mView.findViewById(R.id.name_text);
user_email=(TextView)mView.findViewById(R.id.email_text);
checkBox= (CheckBox) mView.findViewById(R.id.checkBox);
user_name.setText(userName);
user_email.setText(userEmail);
boolean checked=checkBox.isChecked();
}
}
}
This is the model class of the recyclerview
Users.java
package com.tml.sharethem.demo;
/**
* Created by SONI on 01/01/2018.
*/
public class Users {
String name,email;
private boolean isSelected;
public Users(){
}
public Users(String name, String email) {
this.name = name;
this.email = email;
}
public Users(String name, String email, boolean isSelected) {
this.name = name;
this.email = email;
this.isSelected = isSelected;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
This is the xml code for the main recyclerview.
addmembers.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
tools:context="com.tml.sharethem.demo.AddMembers">
<TextView
android:id="#+id/txtGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="25dp"
android:text="" />
<EditText
android:id="#+id/search_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtGroup"
android:layout_marginTop="27dp"
android:background="#drawable/search_layout"
android:ems="10"
android:inputType="textPersonName"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:hint="Search Here..."/>
<ImageButton
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/search_field"
android:layout_marginLeft="34dp"
android:layout_marginStart="34dp"
android:layout_toEndOf="#+id/search_field"
android:layout_toRightOf="#+id/search_field"
app:srcCompat="#android:drawable/ic_menu_search" />
<android.support.v7.widget.RecyclerView
android:id="#+id/result__list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/search_btn"
android:layout_marginTop="10dp">
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/btn_add_members"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Add Selected Members" />
</RelativeLayout>
list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/name_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:layout_marginTop="20dp"
android:text="TextView" />
<TextView
android:id="#+id/email_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name_text"
android:layout_below="#+id/name_text"
android:layout_marginTop="10dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/name_text"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:text="" />
</RelativeLayout>
Implement onCheckChangedListener
One way of doing is
Do the following Modification in
viewHolder.setDetails(model.getName(),model.getEmail());
Change to
viewHolder.setDetails(Users model);
And do the following modification in setDetails()
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked) {
//Store in hashmap
hashmap.put(Users.userId,model)
}else {
if(hashMap.containsKey(model.userId)) {
hashMap.remove(model.userId)
}
}
}
You can use the ArrayList to store id of that particular record, for example, contact id,
then on the click of any control you can retrieve the ids from ArrayList.
public static List<Integer> SelectedCheckbox = new ArrayList<Integer>();
inside recycler view, on checkbox click add or remove values from
arraylist
public ViewHolder(View itemView) {
myCheckBoxContactItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// set tag inside onBindViewHolder method
int contactId = (int) mConvertView.getTag(R.string.contact_id);
if (((CheckBox) v).isChecked() && !SelectedContact.contains(contactId)) {
SelectedContact.add(contactId);
} else if (CommonUtils.SelectedContact.contains(contactId)) {
int indexOf = CommonUtils.SelectedContact.indexOf(contactId);
SelectedContact.remove(indexOf);
}
}
}
myButton.setOnClickListener(new View.OnClickListener() {
for(int i = 0; i< SelectedCheckbox.size; i++)
{
int contactId = SelectedCheckbox.get(i);
// your database query to get record of particular id.
}
}