无法检索列表firebase

时间:2017-07-23 10:44:15

标签: java android firebase firebase-realtime-database

我正在尝试根据我应该从Firebase获取的列表构建自定义适配器。

基本上我设置了我的适配器,然后我设置了一个对我的匹配节点的引用来检索数据,这里奇怪的是它进入了prepareData函数,但它从不进入监听器,没有成功没有错误。

我得到了一个staktrace到我的适配器:

 FATAL EXCEPTION: main
                                                                             Process: com.esmad.pdm.friendlymanager, PID: 9887
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
                                                                                 at com.esmad.pdm.friendlymanager.other.MatchGameAdapter.getItemCount(MatchGameAdapter.java:62)
                                                                                 at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3447)
                                                                                 at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3264)
                                                                                 at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3798)
                                                                                 at android.view.View.layout(View.java:19393)
                                                                                 at android.view.ViewGroup.layout(ViewGroup.java:6022)
                                                                                 at android.support.constraint.ConstraintLayout.onLayout(ConstraintLayout.java:1197)
                                                                                 at android.view.View.layout(View.java:19393)
                                                                                 at android.view.ViewGroup.layout(ViewGroup.java:6022)
                                                                                 at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                                 at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                                 at android.view.View.layout(View.java:19393)
                                                                                 at android.view.ViewGroup.layout(ViewGroup.java:6022)
                                                                                 at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
                                                                                 at android.view.View.layout(View.java:19393)
                                                                                 at android.view.ViewGroup.layout(ViewGroup.java:6022)
                                                                                 at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                                 at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                                 at android.view.View.layout(View.java:19393)
                                                                                 at android.view.ViewGroup.layout(ViewGroup.java:6022)
                                                                                 at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
                                                                                 at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
                                                                                 at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
                                                                                 at android.view.View.layout(View.java:19393)
                                                                                 at android.view.ViewGroup.layout(ViewGroup.java:6022)
                                                                                 at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
                                                                                 at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
                                                                                 at com.android.internal.policy.DecorView.onLayout(DecorView.java:736)
                                                                                 at android.view.View.layout(View.java:19393)
                                                                                 at android.view.ViewGroup.layout(ViewGroup.java:6022)
                                                                                 at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2480)
                                                                                 at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2199)
                                                                                 at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1385)
                                                                                 at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6722)
                                                                                 at android.view.Choreographer$CallbackRecord.run(Choreographer.java:886)
                                                                                 at android.view.Choreographer.doCallbacks(Choreographer.java:698)
                                                                                 at android.view.Choreographer.doFrame(Choreographer.java:633)
                                                                                 at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:872)
                                                                                 at android.os.Handler.handleCallback(Handler.java:769)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                 at android.os.Looper.loop(Looper.java:164)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:6540)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

这是我的活动代码:

public class AllMatches extends AppCompatActivity implements MatchGameAdapter.OnItemClickListener {

    MatchGameAdapter matchGameAdapter;

    RecyclerView recyclerView;

    ArrayList<MatchViewModel> matches;
    FirebaseDatabase database;
    HashMap<String, String> matchesKeys;
    String eventId;
    String eventName;
    DatabaseReference myRef;

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

        Intent i = getIntent();
        Bundle extras = i.getExtras();

        database = FirebaseDatabase.getInstance();
        if(extras.containsKey("eventId")){
            eventId = extras.getString("eventId");
        }

        if(extras.containsKey("matches")) {
            matchesKeys = (HashMap<String, String>) i.getSerializableExtra("matches");
        }

        if(extras.containsKey("eventName")) {
            eventName = extras.getString("eventName");
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);

        recyclerView = (RecyclerView)findViewById(R.id.rv);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(linearLayoutManager);

        matchGameAdapter = new MatchGameAdapter(getApplicationContext(), matches,AllMatches.this);
        recyclerView.setAdapter(matchGameAdapter);

        prepareData();
    }



    private void prepareData() {
        Log.d("hello","hello");
        DatabaseReference myRef = database.getReference("Matches");
        myRef.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                            Log.d("hello","hello2");
                            Match match = snapshot.getValue(Match.class);
                            MatchViewModel matchViewModel = new MatchViewModel(match.getId(),eventId,eventName,match.getGameEnded(),snapshot.child("date").child("day").getValue().toString(), snapshot.child("date").child("month").getValue().toString(),snapshot.child("date").child("year").getValue().toString(),snapshot.child("date").child("hours").getValue().toString(),snapshot.child("date").child("minutes").getValue().toString());
                            Iterator it = matchesKeys.entrySet().iterator();
                            while (it.hasNext()) {
                                Map.Entry pair = (Map.Entry) it.next();
                                it.remove(); // avoids a ConcurrentModificationException
                                if (match.getId().equals(pair.getValue())) {
                                    matches.add(matchViewModel);
                                }
                            }
                        }
                        matchGameAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.d("failed", "here");
                    }

                });
    }

    @Override
    public void onRowClick(String eventId, HashMap<String, Boolean> matches) {

    }
}

和我的适配器:

import java.util.ArrayList;
import java.util.HashMap;


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

    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onRowClick(String eventId, HashMap<String, Boolean> matches);
    }

    private ArrayList<MatchViewModel> matches;
    private Context context;
    private View cv;

    public MatchGameAdapter(Context context, ArrayList<MatchViewModel> matches, OnItemClickListener listener) {
        this.matches = matches;
        this.context = context;
        this.listener = listener;
    }

    @Override
    public MatchGameAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.eventgame, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final MatchGameAdapter.ViewHolder viewHolder, final int i) {
        viewHolder.name.setText(matches.get(i).getEventName() + "  " + i + "ª Semana");
        viewHolder.city.setText(matches.get(i).getDay() + "/" + matches.get(i).getMonth() + "/" + matches.get(i).getYear() + "  " + matches.get(i).getHour() + ":" + matches.get(i).getMinute());
        viewHolder.date.setText(matches.get(i).getHasEnded().toString());
        viewHolder.field.setImageResource(R.drawable.match);

        /*cv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onRowClick(events.get(i).getEventId(),events.get(i).getMatches());
                }
            }
        });*/
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{
        private ImageView field;
        private TextView city;
        private TextView date;
        private TextView name;
        public ViewHolder(View view) {
            super(view);
            cv = view;
            name = (TextView)view.findViewById(R.id.eventName);
            field = (ImageView)view.findViewById(R.id.field);
            city = (TextView)view.findViewById(R.id.city);
            date = (TextView)view.findViewById(R.id.date);

        }
    }

}

2 个答案:

答案 0 :(得分:1)

请阅读您的错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at com.esmad.pdm.friendlymanager.other.MatchGameAdapter.getItemCount(MatchGameAdapter.java:62)

getItemCount 函数尝试获取 null数组的大小。

您只需要使用空数组初始化匹配数组

检查您的数组是否 null

@Override
public int getItemCount() {
    if (matches != null) {
        return matches.size();
    } else {
        return 0;
    }
}

答案 1 :(得分:0)

你得到一个空指针,因为当你启动你的适配器时:

matchGameAdapter = new MatchGameAdapter(getApplicationContext(), matches,AllMatches.this);

您正在传递空列表(matches)。

我看到你正在填充一个Hashmap:

matchesKeys = (HashMap<String, String>) i.getSerializableExtra("matches");

但你永远不会使用它。

在编写此代码时,您似乎非常困惑。