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**
Related
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();
}
});
}}
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();
}
I tried to retrive images from firebase with correct url link. The RecyclerView keep shown "first" info of Food which is cookie-milk-cup:
This is my firebase data structure:
all_uploaded_image //directory
|-cookie milk cup
|-description: "yes!" //shown successful
|-image_uri: "content://com.android.providers.media.documents..." //no necessary in this case
|-name: "cookie milk cup" //shown successful
|-price: "1.20" //not shown
|-uploader_uid: "GSsY4tEo5ZZpS8kkJEpWGLCbFmC3" //no necessary in this case
fish n chips //recursive only on cookie milk cup, so nothing appear in here
|-description: "delicious fc"
|-image_uri: "content://com.android.providers.media.documents..."
|-name: "fish n chips"
|-price: "1.20"
|-uploader_uid: "GSsY4tEo5ZZpS8kkJEpWGLCbFmC3"
I am using android with java, want to get the info from firebase using fragment.
This is the AllFOodFragment.java
public class AllFoodFragment extends Fragment {
private View contactsView;
private ArrayList<Food> entries;
private DatabaseReference ref;
private FirebaseDatabase dbr;
private FoodAdapter adapter;
private RecyclerView recycler_view;
public AllFoodFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contactsView = inflater.inflate(R.layout.home_main, container, false); //v
recycler_view = (RecyclerView) contactsView.findViewById(R.id.recycler_view);
recycler_view.setHasFixedSize(true);
recycler_view.setItemAnimator(new DefaultItemAnimator());
final FragmentActivity ga = getActivity(); //2a
LinearLayoutManager lm = new LinearLayoutManager(ga); //2
recycler_view.setLayoutManager(lm);
entries = new ArrayList<Food>();
ref = FirebaseDatabase.getInstance().getReference().child("all_uploaded_image");
ref.addChildEventListener(new ChildEventListener(){
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot ds: dataSnapshot.getChildren()) {
//Log.e("Count " ,"" + dataSnapshot.getChildrenCount());
Food data = dataSnapshot.getValue(Food.class);
//data.setPrice(dataSnapshot.child("price").getValue().toString());
//data.setImageUrl(dataSnapshot.child("image_uri").getValue().toString());
entries.add(data);
//Log.e("Get All Description", data.get_price());
}
adapter = new FoodAdapter(getActivity(), entries);
adapter.notifyDataSetChanged();
adapter.setListFood(entries);
//3; No adapter attached in here, but program runs
recycler_view.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
return contactsView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onViewCreated(View view, #Nullable Bundle savedUbstabceState){
super.onViewCreated(view, savedUbstabceState);
this.contactsView = view;
}
}
And, this is FoodAdapter.java
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {
private Context m_context;
private ArrayList<Food> m_listFood = new ArrayList<Food>();
public FoodAdapter(Context context, ArrayList<Food> food_list) {//m_context, food_list
this.m_context = context;
this.m_listFood = food_list;
}
#NonNull
#Override
public FoodViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fragment_all_food, parent, false);
return new FoodViewHolder(v);
}
public class FoodViewHolder extends RecyclerView.ViewHolder{
public ImageView FoodIcon;
public TextView FoodName;
public TextView FoodDescription;
public TextView FoodPrice;
public Button Fooddetail;
public FoodViewHolder (View itemView){
super(itemView);
FoodIcon = (ImageView)itemView.findViewById(R.id.thumbnail); //icon
FoodName = itemView.findViewById(R.id.foodname);
FoodDescription = itemView.findViewById(R.id.fooddescription);
FoodPrice = itemView.findViewById(R.id.foodprice);
Fooddetail = itemView.findViewById(R.id.fooddetail);
}
public void onClick(View view) {
}
}
#Override
public void onBindViewHolder(#NonNull FoodViewHolder holder, int position) {
Food f = m_listFood.get(position);
holder.FoodName.setText(f.get_name());
holder.FoodDescription.setText(f.get_description());
holder.FoodPrice.setText(f.get_price());
holder.FoodPrice.setText(f.get_url());
//Picasso.get().load(m_listFood.get(position).get_url()).fit().into(holder.FoodIcon);
Glide.with(m_context).load(f.get_url()).into(holder.FoodIcon); //getListFood().get(position).get_icon()
}
#Override
public int getItemCount() {
return m_listFood.size();
}
public Context get_context() {
return m_context;
}
public void setListFood(ArrayList<Food> m_listFood){
this.m_listFood = m_listFood;
}
}
this is item_fragment_all_food.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView //icon not shown, white
android:id="#+id/thumbnail"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/star_big_on" />
<TextView
android:id="#+id/foodname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="191dp"
android:layout_marginTop="16dp"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/fooddescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/foodname"
android:layout_marginEnd="86dp"
android:layout_marginBottom="-91dp"
android:text="Description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/foodname" />
<TextView
android:id="#+id/foodprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="85dp"
android:layout_marginEnd="95dp"
android:text="Price"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.487"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/fooddescription"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/fooddetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginEnd="79dp"
android:layout_marginBottom="16dp"
android:background="#color/colorPrimary"
android:text="Detail"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/foodprice"
app:layout_constraintVertical_bias="0.0" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And, this is activity_main.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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:autofillHints="email"
android:layout_margin="15dp"
android:inputType="textEmailAddress"
android:hint="Enter Email"
android:id="#+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_margin="15dp"
android:inputType="textPassword"
android:hint="Enter Password"
android:id="#+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:layout_margin="15dp"
android:hint="Register"
android:id="#+id/btn_register"
android:layout_width="match_parent"
android:onClick="click_to_register_new_user"
android:layout_height="wrap_content" />
<Button
android:layout_margin="15dp"
android:hint="Login"
android:id="#+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="137dp"
android:text="#string/reset_string" />
</RelativeLayout>
Lastly, my Food Model
public class Food {
public String name;
public String description;
public String price;
public String img_url;
public String icon;
public Food() {
//empty
}
public Food(String name, String description, String price, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
this.name = name;
this.description = description;
this.price = price;
this.img_url = imageUrl;
}
public String get_name() {
return name;
}
public String get_description() {
return description;
}
public String get_price() {
return price;
}
public String get_icon() {
return icon;
}
public String get_url() {
return img_url;
}
public void setPrice(String price) {
this.price = price;
}
public void setImageUrl(String imageUrl) {
img_url = imageUrl;
}
public void set_icon(String icon) {
this.icon = icon;
}
}
The error I get is E/RecyclerView: No adapter attached; skipping layout
and No setter/field for image_uri found on class com.example.hungrystomach.Model.Food [but really I do not want image_uri shown in my recyclerview so I skip the TextView]
The recyclerView does not have any Image shown even I've FoodIcon with thumbnail in FOodAdaper.java. I've tried for three weeks already still no hope. I suppose to get all the info I need. I know it is little bit long but any suggestion and answer would appreciate.
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.
I made a class named Student, I want to add some objects of students to an arrayList.
I have an activity in java Android and I want to make each object by clicking add button.and simultaneously I want to show student name and address in a custom listview above that activity,that means I want to list students arrayList in a layout.
how should I make an adapter for this arraylist ??
Can anybody complete these code ??
Button btnadd = (Button) findViewById(R.id.btnAdd);
btnadd.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
EditText etname = (EditText) findViewById(R.id.etName);
EditText etaddress = (EditText) findViewById(R.id.etAddress);
RadioGroup typeRadio = (RadioGroup)findViewById(R.id.radioType);
List<Student> rlist = new ArrayList<Student>();
rlist.add(new Student(etname.getText().toString(),
etaddress.getText().toString(),
typeRadio.toString()));
}
}
);
}
private class MyArrayAdapter<String> extends ArrayAdapter<String>{
?
?
?
}
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_layout, parent, false);
ImageView iv = (ImageView) row.findViewById(R.id.resType);
TextView tv1 = (TextView) row.findViewById(R.id.resName);
TextView tv2 = (TextView) row.findViewById(R.id.resAddress);
?
?
?
?
return row;
}
Here's the working code. You can add whatever you want for each row in custom_row.xml.
MainActivity.class
public class MainActivity extends ActionBarActivity {
ListView listView;
CustomAdapter adapter;
ArrayList<Student> studentArrayList;
EditText ename, eaddress;
Button enter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ename = (EditText)findViewById(R.id.eName);
eaddress = (EditText)findViewById(R.id.eAddress);
enter = (Button) findViewById(R.id.enter);
studentArrayList = new ArrayList<Student>();
adapter = new CustomAdapter(this,studentArrayList);
listView.setAdapter(adapter);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String got_name = ename.getText().toString();
String got_address = eaddress.getText().toString();
if (got_name!=null && got_address!=null)
{
Student student = new Student(got_name, got_address);
studentArrayList.add(student);
ename.setText(" ");
eaddress.setText(" ");
adapter.notifyDataSetChanged();
}
}
});
}
private class CustomAdapter extends BaseAdapter {
Context context;
ArrayList<Student> studentArrayList;
public CustomAdapter(MainActivity activity, ArrayList<Student> studentArrayList) {
this.context = activity;
this.studentArrayList = studentArrayList;
}
#Override
public int getCount() {
return studentArrayList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.custom_row, null);
}
TextView studentName = (TextView)v.findViewById(R.id.studentName);
TextView studentAddress = (TextView)v.findViewById(R.id.studentAddress);
studentName.setText(studentArrayList.get(i).getName());
studentAddress.setText(studentArrayList.get(i).getAddress());
return v;
}
}
}
activity_main.xml
<RelativeLayout 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=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:id="#+id/listView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Enter Name : "
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="22dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Enter Address : "
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_alignLeft="#+id/textView"
android:layout_alignStart="#+id/textView"
android:layout_marginTop="20dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/eName"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/listView"
android:layout_alignEnd="#+id/listView"
android:layout_toRightOf="#+id/textView2"
android:layout_toEndOf="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/eAddress"
android:layout_alignBottom="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/enter"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="32dp" />
</RelativeLayout>
Student.class
public class Student {
String name, address;
public Student(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
custom_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="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="New Text"
android:id="#+id/studentName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Medium Text"
android:id="#+id/studentAddress"
android:layout_below="#+id/studentName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Output :