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

时间:2016-12-23 20:39:33

标签: android firebase android-recyclerview

我想从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());
        }
    });

1 个答案:

答案 0 :(得分:7)

您的问题是(ArrayList<String>) dataSnapshot.getValue()有时是null,存储值后,getItemCount会抛出异常。如果您可以在值为null时将0作为大小返回,则解决方案为

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

但是,您可能想了解dataSnapshot.getValue可以返回null的原因。也许这是真正的问题而NullPointerException只是症状。