gpt4 book ai didi

android - 空对象引用上的 java.util.ArrayList.size()'

转载 作者:行者123 更新时间:2023-12-02 06:52:00 25 4
gpt4 key购买 nike

我想从我的 Firebase 数据库中提取数据。我的表名是“cardornek”。我设置了读/写权限。

但是我在空对象引用上得到了这个“java.util.ArrayList.size()'”错误。任何想法?

RecyclerViewAdapter.java

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

private ArrayList<String> values=null;
RecyclerViewAdapter(ArrayList<String> values) {
this.values = values;
}
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_item,parent,false));
}


@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder holder, int position)
{
holder.name.setText(values.get(position));
}

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

public class ViewHolder extends RecyclerView.ViewHolder
{
private TextView name;
ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.list_item_text);
}
}

MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new GetDataFromFirebase().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

// Read from the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("cardornek");

myRef.addValueEventListener(new ValueEventListener() {


@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> values = (ArrayList<String>) dataSnapshot.getValue();
recyclerView.setAdapter(new RecyclerViewAdapter(values));
}

@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("Failed to read value." + databaseError.toException());
}
});

最佳答案

你的问题是 (ArrayList<String>) dataSnapshot.getValue()有时是 null存储值后,getItemCount 中会引发异常.如果您可以在值为 null 时返回 0 作为大小,那么解决方案是

@Override
public int getItemCount() {
return (values == null) ? 0 : values.size();
}

但是,您可能想知道为什么 dataSnapshot.getValue可以返回 null .也许这才是真正的问题, NullPointerException只是症状。

关于android - 空对象引用上的 java.util.ArrayList.size()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41307596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com