无法在Android Studio中使用RecyclerView显示联系人列表。

huangapple go评论63阅读模式
英文:

Unable to display contact list in Android Studio using RecyclerView

问题

我正在尝试在我的移动应用程序中显示我的联系人列表。我已经连接了数据库,我发现数据库没有问题,因为我可以添加新联系人,但是我无法显示列表。我使用了RecyclerView,我已经创建了适配器类、项目布局和模型。

  • 适配器类 - contAdapter.java
  • 项目布局 - item.xml
  • 模型 - Contact
  • RecyclerView 布局 - contactList.xml
  • contactList - 用于将 RecyclerView 与适配器绑定

我希望看到已添加到数据库的联系人列表显示在屏幕上,但我已经卡在这里很长时间,因为我无法找出问题在哪里 无法在Android Studio中使用RecyclerView显示联系人列表。

这是我的联系人模型:

public Contact() {
    
}

public Contact(String contName, String contNumber) {
    this.contName = contName;
    this.contNumber = contNumber;
}

public String getContName() {
    return contName;
}

public void setContName(String contName) {
    this.contName = contName;
}

public String getContNumber() {
    return contNumber;
}

public void setContNumber(String contNumber) {
    this.contNumber = contNumber;
}

contactList.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
    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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="25dp"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/contList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

contactList.java

package com.example.lucentproj;

import androidx.annotation.NonNull; 
import androidx.appcompat.app.AppCompatActivity; 
import androidx.recyclerview.widget.LinearLayoutManager; 
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth; 
import com.google.firebase.auth.FirebaseUser; 
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 java.util.ArrayList;

public class contactList extends AppCompatActivity {
    RecyclerView recyclerView;
    DatabaseReference reference;
    contAdapter adapter;
    ArrayList<Contact> list;
    FirebaseUser user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_list);

        user = FirebaseAuth.getInstance().getCurrentUser();
        recyclerView = findViewById(R.id.contList);
        reference = FirebaseDatabase.getInstance().getReference("Contact");
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        list = new ArrayList<>();
        adapter = new contAdapter(this, list);
        recyclerView.setAdapter(adapter);

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {

                    Contact contact = dataSnapshot.getValue(Contact.class);
                    list.add(contact);

                }
                adapter.updateList(list);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
}

item.xml

<?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="16dp"
    app:cardElevation="8dp" app:cardCornerRadius="8dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:orientation="vertical"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal" />

    <TextView
        android:id="@+id/contname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/amaranth"
        android:text="Name"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="8dp"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/contno"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:fontFamily="@font/amaranth_italic"
        android:paddingLeft="10dp"
        android:text="Number"
        android:textSize="20dp"
        android:textStyle="italic" />

    <ImageView
        android:id="@+id/cCall"
        android:layout_width="38dp"
        android:layout_height="30dp"
        android:layout_marginLeft="280dp"
        android:layout_marginTop="15dp"
        android:clickable="true"
        android:src="@drawable/call" />

    <ImageView
        android:id="@+id/cEdit"
        android:layout_width="45dp"
        android:layout_height="30dp"
        android:layout_marginLeft="320dp"
        android:layout_marginTop="15dp"
        android:clickable="true"
        android:src="@drawable/edit" />
</androidx.cardview.widget.CardView>

contAdapter

package com.example.lucentproj;

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 java.util.ArrayList;

public class contAdapter extends RecyclerView.Adapter<contAdapter.ViewHolder> {
    Context context;
    ArrayList<Contact> list;

    public contAdapter(Context context, ArrayList<Contact> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Contact cont = list.get(position);
        holder.cname.setText(cont.getContName());
        holder.cnum.setText(cont.getContNumber());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView cname

<details>
<summary>英文:</summary>

I am trying to display my contact list for my mobile application. I have already connected the database and I figured that there is no problem with the database since I can add new contact but I am unable to display the list. I use RecyclerView which I already created Adapter class, item layout and model for.

* Adapter class - contAdapter.java
* item layout - item.xml
* Model - Contact
* RecyclerView Layout - contactList.xml
* contactList - to bind recyclerview with adapter

I wish to see the list of contact added to the database to be displayed on the screen but I have been stuck here for quite some time since I cannot figure out what the problem is :(

Here is my Contact Model:

    public Contact() {
    
    }
    
    public Contact(String contName, String contNumber) {
    this.contName = contName;
    this.contNumber = contNumber;
    }
    
    public String getContName() {
    return contName;
    }
    
    public void setContName(String contName) {
    this.contName = contName;
    }
    
    public String getContNumber() {
    return contNumber;
    }
    
    public void setContNumber(String contNumber) {
    this.contNumber = contNumber;
    }

`contactList.xml`:

```xml
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;

        &lt;androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
        android:layout_margin=&quot;25dp&quot; tools:context=&quot;.MainActivity&quot;&gt;
    
        &lt;androidx.recyclerview.widget.RecyclerView
        android:id=&quot;@+id/contList&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;/&gt;
        &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

contactList.java:

    package com.example.lucentproj;
import androidx.annotation.NonNull; 
import androidx.appcompat.app.AppCompatActivity; 
import androidx.recyclerview.widget.LinearLayoutManager; 
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth; 
import com.google.firebase.auth.FirebaseUser; 
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 java.util.ArrayList;
public class contactList extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference reference;
contAdapter adapter;
ArrayList&lt;Contact&gt; list;
FirebaseUser user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
user = FirebaseAuth.getInstance().getCurrentUser();
recyclerView = findViewById(R.id.contList);
reference = FirebaseDatabase.getInstance().getReference(&quot;Contact&quot;);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList&lt;&gt;();
adapter = new contAdapter(this, list);
recyclerView.setAdapter(adapter);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Contact contact = dataSnapshot.getValue(Contact.class);
list.add(contact);
}
adapter.updateList(list);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}

item.xml:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;

        &lt;androidx.cardview.widget.CardView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot;
        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:layout_margin=&quot;16dp&quot;
        app:cardElevation=&quot;8dp&quot; app:cardCornerRadius=&quot;8dp&quot;&gt;
    
    
        &lt;LinearLayout
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginLeft=&quot;16dp&quot;
        android:orientation=&quot;vertical&quot;/&gt;
    
        &lt;LinearLayout
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_gravity=&quot;center_vertical&quot;
        android:orientation=&quot;horizontal&quot; /&gt;
    
        &lt;TextView
        android:id=&quot;@+id/contname&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:fontFamily=&quot;@font/amaranth&quot;
        android:text=&quot;Name&quot;
        android:layout_marginLeft=&quot;10dp&quot;
        android:layout_marginTop=&quot;8dp&quot;
        android:textSize=&quot;20sp&quot;
        android:textStyle=&quot;bold&quot; /&gt;
    
        &lt;TextView
        android:id=&quot;@+id/contno&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginTop=&quot;30dp&quot;
        android:fontFamily=&quot;@font/amaranth_italic&quot;
        android:paddingLeft=&quot;10dp&quot;
        android:text=&quot;Number&quot;
        android:textSize=&quot;20dp&quot;
        android:textStyle=&quot;italic&quot; /&gt;
    
        &lt;ImageView
        android:id=&quot;@+id/cCall&quot;
        android:layout_width=&quot;38dp&quot;
        android:layout_height=&quot;30dp&quot;
        android:layout_marginLeft=&quot;280dp&quot;
        android:layout_marginTop=&quot;15dp&quot;
        android:clickable=&quot;true&quot;
        android:src=&quot;@drawable/call&quot; /&gt;
    
        &lt;ImageView
        android:id=&quot;@+id/cEdit&quot;
        android:layout_width=&quot;45dp&quot;
        android:layout_height=&quot;30dp&quot;
        android:layout_marginLeft=&quot;320dp&quot;
        android:layout_marginTop=&quot;15dp&quot;
        android:clickable=&quot;true&quot;
        android:src=&quot;@drawable/edit&quot; /&gt;
    
    &lt;/androidx.cardview.widget.CardView&gt;

contAdapter:

package com.example.lucentproj;
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 java.util.ArrayList;
public class contAdapter extends RecyclerView.Adapter&lt;contAdapter.ViewHolder&gt; {Context context;
ArrayList&lt;Contact&gt; list;
public contAdapter(Context context, ArrayList&lt;Contact&gt; list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Contact cont = list.get(position);
holder.cname.setText(cont.getContName());
holder.cnum.setText(cont.getContNumber());
}
@Override
public int getItemCount() {
return list.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView cname, cnum;
public ViewHolder(@NonNull View itemView) {
super(itemView);
cname = itemView.findViewById(R.id.contName);
cnum =  itemView.findViewById(R.id.contNumber);
}
}
public void updateList(ArrayList&lt;Contact&gt; list){
this.list=list;
notifyDataSetChanged();
}
}

答案1

得分: 1

你没有在适配器中更新列表

请在你的适配器类中添加这个方法 -

public void updateList(ArrayList<Contact> list){
   this.list = list;
   notifyDataSetChanged();
}

并且将联系列表活动中的这一行代码替换为 adapter.updateList(list);,而不是 adapter.notifyDataSetChanged();

contactList.java

package com.example.lucentproj;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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 java.util.ArrayList;

public class contactList extends AppCompatActivity {
    RecyclerView recyclerView;
    DatabaseReference reference;
    contAdapter adapter;
    ArrayList<Contact> list;
    FirebaseUser user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_list);

        user = FirebaseAuth.getInstance().getCurrentUser();
        recyclerView = findViewById(R.id.contList);
        reference = FirebaseDatabase.getInstance().getReference("Contact");
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        list = new ArrayList<>();

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                list.clear(); // 清空列表以防止重复添加
                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    Contact contact = dataSnapshot.getValue(Contact.class);
                    list.add(contact);
                }
                adapter.updateList(list); // 更新适配器的数据
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

        adapter = new contAdapter(this, list);
        recyclerView.setAdapter(adapter);
    }
}

请确保按照上述方式更新你的代码。

英文:

You are not updating list in Adaptor

Please add this method in your adaptor class -

public void updateList(ArrayList&lt;Contact&gt; list){
this.list=list;
notifyDataSetChanged();
}

And replace this line from your contactList activity to adapter.notifyDataSetChanged(); --> adapter.updateList(list);

contactList.java

   package com.example.lucentproj;
import androidx.annotation.NonNull; 
import androidx.appcompat.app.AppCompatActivity; 
import androidx.recyclerview.widget.LinearLayoutManager; 
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth; 
import com.google.firebase.auth.FirebaseUser; 
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 java.util.ArrayList;
public class contactList extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference reference;
contAdapter adapter;
ArrayList&lt;Contact&gt; list;
FirebaseUser user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
user = FirebaseAuth.getInstance().getCurrentUser();
recyclerView = findViewById(R.id.contList);
reference = FirebaseDatabase.getInstance().getReference(&quot;Contact&quot;);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList&lt;&gt;();
myRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Contact contact = dataSnapshot.getValue(Contact.class);
list.add(contact);
}
}
adapter = new contAdapter(this, list);
recyclerView.setAdapter(adapter);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Contact contact = dataSnapshot.getValue(Contact.class);
list.add(contact);
}
adapter.updateList(list);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}

huangapple
  • 本文由 发表于 2023年1月9日 14:32:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053844.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定