App crashes while setting a CircleImageView with Picasso in FirebaseRecyclerAdapter [duplicate] - java

This question already has answers here:
Picasso IllegalArgumentException Target must not be null
(7 answers)
Closed 3 years ago.
I'm trying to display a RecyclerView with data from firebase.
I don't know why I get this error:
Process: com.example.lapitchat, PID: 29868
java.lang.IllegalArgumentException: Target must not be null.
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:682)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:665)
at com.example.lapitchat.UsersActivity$1.onBindViewHolder(UsersActivity.java:65)
at com.example.lapitchat.UsersActivity$1.onBindViewHolder(UsersActivity.java:61)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:122)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1888)
at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:407)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
at android.view.Choreographer.doCallbacks(Choreographer.java:761)
at android.view.Choreographer.doFrame(Choreographer.java:693)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
That's in my UsersActivity, there I want to display that RecyclerView. I also have the ViewHolder in it. model.getImage() gives the image download Url, and I don't know why I can't store the image in holder.singleImage.
public class UsersActivity extends AppCompatActivity {
private Toolbar mToolbar;
private RecyclerView mUsersList;
private DatabaseReference mUsersDatabase;
private FirebaseRecyclerOptions<Users> options;
private FirebaseRecyclerAdapter<Users, UsersViewHolder> adapter;
private static final String TAG = "UsersActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
mToolbar = findViewById(R.id.users_appBar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("All Users");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersList = findViewById(R.id.users_list);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new LinearLayoutManager(this));
options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(mUsersDatabase, Users.class).build();
adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull Users model) {
Picasso.get().load(model.getImage()).into(holder.singleImage);
holder.singleName.setText(model.getName());
holder.singleStatus.setText(model.getStatus());
}
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new UsersViewHolder(view);
}
};
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
mUsersList.setAdapter(adapter);
}
#Override
protected void onPause() {
super.onPause();
adapter.stopListening();
mUsersList.setAdapter(adapter);
}
public class UsersViewHolder extends RecyclerView.ViewHolder {
TextView singleName;
TextView singleStatus;
CircleImageView singleImage;
UsersViewHolder(#NonNull View itemView) {
super(itemView);
singleName = findViewById(R.id.user_single_name);
singleStatus = findViewById(R.id.user_single_status);
singleImage = findViewById(R.id.user_single_image);
}
}
}
That's my Users.java code:
package com.example.lapitchat;
public class Users {
public String image;
public String name;
public String status;
public Users() {
//needed
}
public Users(String name, String image, String status) {
this.image = image;
this.name = name;
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Other files that might be useful:
The layout for the activity is activity_users.xml:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".UsersActivity">
<include
android:id="#+id/users_appBar"
layout="#layout/app_bar_layout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.RecyclerView
android:id="#+id/users_list"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/users_appBar">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
And the list item layout users_single_layout.xml is the following.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/user_single_image"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:src="#drawable/avatar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:src="#drawable/avatar" />
<TextView
android:id="#+id/user_single_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="20dp"
android:text="TextView"
android:textColor="#android:color/background_dark"
android:textSize="18sp"
app:layout_constraintStart_toEndOf="#+id/user_single_image"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/user_single_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="10dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/user_single_image"
app:layout_constraintTop_toBottomOf="#+id/user_single_name" />
</android.support.constraint.ConstraintLayout>
Also, how my database looks:

Some things are still not very clear to me. However, I think this is not the complete data that you are having in your Firebase database. I suppose you are getting an array of users. Hence your initialization to the firebase adapter needs to be modified like the following.
options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(mUsersDatabase, Users[].class).build(); // Use the array
Your Users class needs to have another attribute which is missing as well I think.
public class Users {
public String image;
public String name;
public String status;
public String thumb_image; // This is missing
}
The others look okay to me. Let me know if that solves your problem.

Related

Getting error of : Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

I have seen all stack overflow question about this but can't find solution.
Getting error at this line.
String p_score = player_score_US.getText().toString();
My code
public class UpdateScore_activity extends AppCompatActivity {
private RecyclerView recyclerView2;
private DatabaseReference root=FirebaseDatabase.getInstance().getReference("A_matches&Score&contest").child("1").child("Score");
private us_adapter usAdapter;
private TextView playerName;
private Button SaveScorebtn;
public ArrayList<us_model> list1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatescore);
recyclerView2=findViewById(R.id.recycleview2);
SaveScorebtn=(Button)findViewById(R.id.us_saveScore);
EditText player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
playerName=(TextView) findViewById(R.id.Player_Name);
list1=new ArrayList<>();
usAdapter=new us_adapter(this,list1);
recyclerView2.setAdapter(usAdapter);
recyclerView2.setLayoutManager(new LinearLayoutManager(this));
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
String name1 = dataSnapshot.child("Name").getValue(String.class);
us_model myModel=new us_model(name1);
list1.add(myModel);
}
usAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(UpdateScore_activity.this, "hello", Toast.LENGTH_SHORT).show();
}
});
SaveScorebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String p_score = player_score_US.getText().toString();
HashMap<String, String> usermap = new HashMap<>();
usermap.put("Score",p_score);
for (int i=1;i<4;i++){
root.child(String.valueOf(i)).setValue(usermap);
}
openMain();
}
});
}}
Layout file of update Score Activity(Recyclerview)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="#ffffff"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="500dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Match_Name"
android:gravity="center_horizontal"
android:text="Update Score"
android:textAlignment="center"
android:textColor="#000002"
android:textSize="32dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="456dp"
android:layout_marginTop="10dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleview2"
android:layout_width="match_parent"
android:layout_height="441dp" />
</LinearLayout>
<Button
android:id="#+id/us_saveScore"
android:layout_width="127dp"
android:layout_height="match_parent"
android:layout_marginLeft="62pt"
android:layout_marginTop="5dp"
android:layout_marginRight="57dp"
android:background="#FF80AB"
android:text="Save Score"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Layout file of player card
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="115dp"
android:layout_marginTop="10dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="111dp"
app:cardBackgroundColor="#A6D673">
<TextView
android:id="#+id/Player_Name"
android:layout_width="256dp"
android:layout_height="71dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Player Name"
android:textColor="#000000"
android:textSize="25dp"
android:textStyle="bold" />
<EditText
android:id="#+id/us_Player_Score12"
android:layout_width="79dp"
android:layout_height="61dp"
android:layout_marginLeft="300dp"
android:layout_marginTop="19dp"
android:gravity="center_horizontal"
android:textAlignment="center"
android:textColor="#000000"
android:hint="Enter"
android:textSize="22dp"
android:textStyle="bold" />
</androidx.cardview.widget.CardView>
</LinearLayout>
Adapter class
public class us_adapter extends RecyclerView.Adapter<us_adapter.Myviewholder> {
ArrayList<us_model> mlist1;
Context context;
public us_adapter(Context context, ArrayList<us_model> mlist1){
this.context=context;
this.mlist1=mlist1;
}
public us_adapter.Myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v=LayoutInflater.from(context).inflate(R.layout.updatescore_row,parent,false);
return new Myviewholder(v);
}
#Override
public void onBindViewHolder(#NonNull Myviewholder holder, int position) {
us_model model1 =mlist1.get(position);
holder.Name.setText(model1.getName());
}
public int getItemCount() {
return mlist1.size();
}
public class Myviewholder extends RecyclerView.ViewHolder {
TextView Name;
Button update;
public Myviewholder(#NonNull View itemView) {
super(itemView);
Name=itemView.findViewById(R.id.Player_Name);
}
}
}
Model class
public class us_model{
private String Name;
public us_model(String Name) {
this.Name = Name;
}
public String getName() {
return Name;
}
}
There are two solutions that you could try for this problem.
Solution 1:
From
EditText player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
To
final EditText player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
The reason is, if two methods see the same local variable in Java, Java wants you to ensure you will not change it, In that case you have to make it final.
Solution 2:
As well as, you could make it a global variable.
public class UpdateScore_activity extends AppCompatActivity {
private RecyclerView recyclerView2;
private DatabaseReference root=FirebaseDatabase.getInstance().getReference("A_matches&Score&contest").child("1").child("Score");
private us_adapter usAdapter;
private TextView playerName;
private Button SaveScorebtn;
private EditText player_score_US;
public ArrayList<us_model> list1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatescore);
recyclerView2=findViewById(R.id.recycleview2);
SaveScorebtn=(Button)findViewById(R.id.us_saveScore);
player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
playerName=(TextView) findViewById(R.id.Player_Name);
list1=new ArrayList<>();
usAdapter=new us_adapter(this,list1);
recyclerView2.setAdapter(usAdapter);
recyclerView2.setLayoutManager(new LinearLayoutManager(this));
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
String name1 = dataSnapshot.child("Name").getValue(String.class);
us_model myModel=new us_model(name1);
list1.add(myModel);
}
usAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(UpdateScore_activity.this, "hello", Toast.LENGTH_SHORT).show();
}
});
SaveScorebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String p_score = player_score_US.getText().toString();
HashMap<String, String> usermap = new HashMap<>();
usermap.put("Score",p_score);
for (int i=1;i<4;i++){
root.child(String.valueOf(i)).setValue(usermap);
}
openMain();
}
});
}}

Adapter returns null value

I am trying to load a RecyclerView with data, but I get a NullPointerException every time I want to load the RecyclerView. (The RecyclerView is displayed in a Dialog). First, I have this class:
public class FondosClase {
private int recurso;
private String nombre;
public int getRecurso() {
return recurso;
}
public void setRecurso(int recurso) {
this.recurso = recurso;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public FondosClase(){}
public FondosClase(int recurso, String nombre) {
this.recurso = recurso;
this.nombre = nombre;
}
}
Then my adapter:
public class AdaptadorMenuIzq extends RecyclerView.Adapter<AdaptadorMenuIzq.ViewHolder>{
private FondosClase[] fondosClaseArrayList;
private Context context;
public AdaptadorMenuIzq(FondosClase[] fondosClaseArrayList, Context context) {
this.fondosClaseArrayList = fondosClaseArrayList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutInflater = LayoutInflater.from(parent.getContext()).inflate(R.layout.design_rv_bg_men_izq, parent, false);
return new AdaptadorMenuIzq.ViewHolder(layoutInflater);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final FondosClase fondosClase = fondosClaseArrayList[position];
holder.textView.setText(fondosClase.getNombre());
holder.imageView.setImageResource(fondosClase.getRecurso());
}
#Override
public int getItemCount() {
return fondosClaseArrayList.length;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
this.imageView = itemView.findViewById(R.id.imageView);
this.textView = itemView.findViewById(R.id.textView);
}
}
}
Then create a class where I create the method for Dialog:
public class Alertas {
private AdaptadorMenuIzq adaptadorMenuIzq;
public void AlertaMenuIzquierdoFondo(Context context){
LayoutInflater layoutInflater = LayoutInflater.from(context);
Dialog anuncio = new Dialog(context, R.style.FondoDialog);
final View view = layoutInflater.inflate(R.layout.alerta_fondo_tarjeta_cv_rv, null);
final RecyclerView rv = view.findViewById(R.id.rv_tarjetas);
FondosClase[] fondosClases = new FondosClase[]{
new FondosClase(R.drawable.permanent_bg_a, "a"),
new FondosClase(R.drawable.permanent_bg_b, "b")
};
adaptadorMenuIzq = new AdaptadorMenuIzq(fondosClases, context);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(context));
rv.setAdapter(adaptadorMenuIzq);
anuncio.setContentView(view);
anuncio.show();
}
}
And from my MainActivity I run it through a FAB:
binding.appBarMain.fab.setOnClickListener(view ->{
alertas = new Alertas();
alertas.AlertaMenuIzquierdoFondo(MainActivity.this);
}
);
When I press the button to show it I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.frabasoft.genshinimpactrecursos.Adaptadores.AdaptadorMenuIzq.onBindViewHolder(AdaptadorMenuIzq.java:35)
The line that marks the error is the following:
holder.textView.setText(fondosClase.getNombre());
I changed it to:
holder.textView.setText(fondosClaseArrayList[position].geNombre());
But, the result was the same.
I attach the xml:
alerta_fondo_tarjeta_cv_rv:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_gravity="center"
app:cardCornerRadius="75dp"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="25dp"
android:layout_marginRight="25dp"
android:layout_marginBottom="25dp"
android:layout_marginLeft="25dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv_tarjetas"
android:layout_marginTop="25dp"
android:layout_marginRight="25dp"
android:layout_marginBottom="25dp"
android:layout_marginLeft="25dp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
design_rv_bg_menu_izq:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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"
style="#style/CardView.Light"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:elevation="5dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/ivIcon"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#mipmap/ic_launcher"
android:layout_margin="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvIcon"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#mipmap/ic_launcher"
android:layout_margin="8dp"
android:text="HOLA"
android:gravity="center"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
Does someone tell me what data I'm going wrong?
in the view holder you are not passing your XML view id's
it should be:
this.imageView = itemView.findViewById(R.id.ivIcon);
this.textView = itemView.findViewById(R.id.tvIcon);

Not Getting Data into my Recycler View using Firebase [duplicate]

This question already has answers here:
FirebaseListAdapter not pushing individual items for chat app - Firebase-Ui 3.1
(2 answers)
Closed 2 years ago.
My RecyclerView is not displaying any data.
buynow.java
public class buynow extends AppCompatActivity {
private RecyclerView recyclerView;
DatabaseReference ProductRef;
private EditText searchField;
private Button search_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buynow);
ProductRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
searchField = (EditText) findViewById(R.id.search_field);
search_btn = (Button) findViewById(R.id.search_button);
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseUserSearch();
}
});
}
private void firebaseUserSearch(){
FirebaseRecyclerOptions<Products> options = new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(ProductRef,Products.class).build();
FirebaseRecyclerAdapter<Products, UsersViewHolder> firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<Products, UsersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull
Products model) {
holder.setDetails(model.getPname(), model.getPprice(), model.getPmrp(),
model.getPcondition(), model.getPimage());
}
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
//View Holder Class
public class UsersViewHolder extends RecyclerView.ViewHolder{
View mView;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(String phoneName, String phonePrice, String phoneMrp, String
phoneCondition, String phoneImage){
TextView phone_name = (TextView) mView.findViewById(R.id.product_name);
TextView phone_price = (TextView) mView.findViewById(R.id.product_price);
TextView phone_mrp = (TextView) mView.findViewById(R.id.product_mrp);
TextView phone_condition = (TextView) mView.findViewById(R.id.product_condition);
ImageView phone_image = (ImageView)mView.findViewById(R.id.product_image);
phone_name.setText(phoneName);
phone_price.setText(phonePrice);
phone_mrp.setText(phoneMrp);
phone_condition.setText(phoneCondition);
Picasso.with(getApplicationContext()).load(phoneImage).into(phone_image);
}
}
}
Products.java
public class Products {
private String pname,pprice,pimage,pmrp,pcondition;
public Products(){
}
public Products(String pname, String pprice, String pimage, String pmrp, String pcondition) {
this.pname = pname;
this.pprice = pprice;
this.pimage = pimage;
this.pmrp = pmrp;
this.pcondition = pcondition;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getPprice() {
return pprice;
}
public void setPprice(String pprice) {
this.pprice = pprice;
}
public String getPimage() {
return pimage;
}
public void setPimage(String pimage) {
this.pimage = pimage;
}
public String getPmrp() {
return pmrp;
}
public void setPmrp(String pmrp) {
this.pmrp = pmrp;
}
public String getPcondition() {
return pcondition;
}
public void setPcondition(String pcondition) {
this.pcondition = pcondition;
}
}
Layout for RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:background="#color/primanrybg">
<RelativeLayout
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/buyphones_layout_bg">
<ImageView
android:id="#+id/product_image"
android:layout_width="60dp"
android:layout_height="90dp"
android:src="#drawable/rapid_pickup_foreground" />
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:textSize="16sp"
android:textColor="#color/black"
android:paddingStart="16dp"
android:paddingBottom="4dp"
android:text="iPhone 6s Space Grey (64GB)"/>
<LinearLayout
android:id="#+id/condition"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_marginLeft="16dp"
android:background="#drawable/search_frame"
android:layout_below="#id/product_name"
android:layout_marginBottom="3dp"
android:padding="2dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/yes_no_bg"
android:textColor="#color/white"
android:paddingStart="4dp"
android:padding="1dp"
android:paddingEnd="4dp"
android:text="Condition:" />
<TextView
android:id="#+id/product_condition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginRight="3dp"
android:padding="1dp"
android:textColor="#color/black"
android:text="Like New" />
</LinearLayout>
<TextView
android:id="#+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/condition"
android:layout_toRightOf="#+id/product_image"
android:textSize="18sp"
android:textColor="#color/black"
android:paddingStart="16dp"
android:text="9,9999"/>
<TextView
android:id="#+id/product_mrp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/product_price"
android:layout_below="#id/condition"
android:textSize="18sp"
android:text="24000"
android:textColor="#color/grey"
android:paddingStart="10dp"/>
I am not getting data into my RecyclerView. It is just not showing anything no error nothing. Any help is very appreciated.
I am getting my data from firebase and putting them into the recyclerview to display a list of products.
I would be really great if you can point out what is wrong with my code so that i can correct it.
You need to add startListening() to start listening for data in firebaseui:
The FirebaseRecyclerAdapter uses an event listener to monitor changes to the Firebase query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference in my Adapter class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm having these error on my coding
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference onBindViewHolder(BrandAdapter.java:67) and
BrandAdapter.onBindViewHolder(BrandAdapter.java:34).
I'm not really sure what went wrong as I follow the tutorial very closely. And my database is not empty.
It contains child.
this is my adapter class
public class BrandAdapter extends RecyclerView.Adapter<BrandAdapter.MyViewHolder> {
private Context context;
List<String> key;
ArrayList<Brand> brandList;
public BrandAdapter(ArrayList<Brand> brandList) {
this.brandList = brandList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.brand_list, viewGroup, false);
context = viewGroup.getContext();
return new BrandAdapter.MyViewHolder(view);
}
public BrandAdapter(Context c) {
this.context = c;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.brand_name.setText(brandList.get(i).getBrand_name());
Picasso.with(context).load(brandList.get(i).getBrand_image()).into(myViewHolder.image);
// Picasso.with(mcontext).load(brand.getBrand_image()).into(myViewHolder.image);
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String bName = brandList.get(i).getBrand_name();
String pic = brandList.get(i).getBrand_image();
Log.i("loz", bName);
Intent intent = new Intent(context, updateBrand.class);
intent.putExtra("brand_name", bName);
intent.putExtra("imgurl", pic);
context.startActivity(intent);
}
});
#Override
public int getItemCount() {
return brandList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView brand_name;
CardView brand_cv;
ImageView image, btnDelete;
LinearLayout frame_layout;
public MyViewHolder(View itemView) {
super(itemView);
brand_name = itemView.findViewById(R.id.name);
image = itemView.findViewById(R.id.image);
brand_cv = itemView.findViewById(R.id.brand_cv);
btnDelete = itemView.findViewById(R.id.delete);
frame_layout = itemView.findViewById(R.id.frame_layout);
}
}
}
my Brand Activity class
public class BrandActivity extends AppCompatActivity {
DatabaseReference databaseReference;
ArrayList<Brand> brandList;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brand);
databaseReference = FirebaseDatabase.getInstance().getReference("Brand").child("");
recyclerView = findViewById(R.id.rv);
searchView = findViewById(R.id.searchView);
}
#Override
protected void onStart() {
super.onStart();
if (databaseReference != null) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
brandList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
brandList.add(ds.getValue(Brand.class));
}
}
BrandAdapter brandAdapter = new BrandAdapter(brandList);
recyclerView.setAdapter(brandAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(BrandActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
<androidx.cardview.widget.CardView 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="match_parent"
android:layout_margin="20dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/lightgray">
<TextView
android:id="#+id/brand_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sample"
android:textStyle="bold"
android:textColor="#color/white"
android:textAlignment="center"
android:background="#color/black"
android:textSize="20sp"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#FCFAFA"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/delete"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="8dp"
android:visibility="visible"
app:srcCompat="#drawable/trash" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000" />
</androidx.cardview.widget.CardView>
Brand model
public class Brand {
public String brand_id;
public String brand_name;
public String brand_image;
public Brand(){}
public Brand(String brand_id, String brand_name, String brand_image) {
this.brand_id = brand_id;
this.brand_name = brand_name;
this.brand_image = brand_image;
}
public String getBrand_id() {
return brand_id;
}
public void setBrand_id(String brand_id) {
this.brand_id = brand_id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getBrand_image() {
return brand_image;
}
public void setBrand_image(String brand_image) {
this.brand_image = brand_image;
}
}
In your MyViewHolder you are trying to find view that doesn't exist in your layout. So, try to change brand_name = itemView.findViewById(R.id.name) to brand_name = itemView.findViewById(R.id.brand_name). The same problem is also related to the other views in layout except image and delete: you don't have views with brand_cv and frame_layout ids.

Doesn't show users in RecyclerView while using FirestoreRecyclerAdapter and DocumentReference

I am working on Cloud Firestore. My Firestore database document name is users and I want to show all users in Android RecyclerView and my activity name MainActivity and I'm using this XML file activity_main.xml.
It will showing a blank activity while on running.
activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context="com.example.anuragtiwari.recyclerdemo.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="#+id/recyclerview_list"
android:layout_marginBottom="8dp"
android:layout_marginEnd="7dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="7dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.073"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
android:layout_alignParentTop="true">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView mUsersList;
private CollectionReference muser;
private FirestoreRecyclerAdapter adapter;
LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsersList = (RecyclerView) findViewById(R.id.recyclerview_list);
mUsersList.setLayoutManager(new LinearLayoutManager(this));
muser = FirebaseFirestore.getInstance().collection("users");
Query query = muser;
FirestoreRecyclerOptions<Users> options = new FirestoreRecyclerOptions.Builder<Users>()
.setQuery(query, Users.class).build();
FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<Users, FriendsHolder>(options)
{
#Override
public FriendsHolder onCreateViewHolder(ViewGroup group, int i)
{
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.single_user, group, false);
return new FriendsHolder(view);
}
#Override
public void onError(FirebaseFirestoreException e)
{
Log.e("error", e.getMessage());
}
#Override
protected void onBindViewHolder(FriendsHolder holder, int position, Users model) {
holder.nameText.setText(model.getName());
holder.emailText.setText(model.getEmail());
}
};
mUsersList.setAdapter(adapter);
}
private class FriendsHolder extends RecyclerView.ViewHolder
{
View mView;
public TextView nameText;
public TextView emailText;
public FriendsHolder(View itemview) {
super(itemview);
mView = itemview;
nameText = (TextView) mView.findViewById(R.id.single_user_name);
emailText = (TextView) mView.findViewById(R.id.single_user_email);
}
}
}
single_user.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_margin="15dp"
android:layout_height="match_parent">
<TextView
android:id="#+id/single_user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="27dp"
android:layout_marginStart="27dp"
android:text="Display Name"
android:textColor="#android:color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/single_user_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/single_user_name"
android:layout_alignStart="#+id/single_user_name"
android:layout_below="#+id/single_user_name"
android:layout_marginTop="15dp"
android:text="User Email" />
<view
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="60dp"
/>
</RelativeLayout>
Users.java
public class Users
{
public String name;
public String email;
public Users(){
}
public String getName() {
return name;
}
public void setName(String name) {
name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
email = email;
}
public Users(String name, String email) {
this.name = name;
this.email = email;
}
}
**App Images**

Categories