FirebaseRecyclerAdapter对我不起作用

时间:2016-05-09 12:59:48

标签: java android firebase pojo firebase-realtime-database

我需要父键及其子键来表示RecyclerView中的纬度和经度列表。我猜我需要对LatLngsModel item中的populateViewHolder做一些事情。在FirebaseRecyclerAdapter{ "users" : { "0057242b-81e2-4f97-bca7-b671212614ba" : { "email" : "kalle@hotmail.se", "waypoints" : { "-KH9UAPH5NmLJExaUa5g" : { "-KH9UAPH5NmLJExaS2s" : { "latitude" : 111, "longitude" : 111.1 } }, "-KHB1VjqUdO90vxj9XCh" : { "-KHB1VjqUdO90vxj9XCi" : { "latitude" : 222.1, "longitude" : 222.11 }, "-KHB1ZykbwgXM9sPNie9" : { "latitude" : 222.2, "longitude" : 222.22 } } } }, ,但无论我做什么,我都没有做对。

我目前通过所有父键循环所有父键,并将其添加到列表...

JSON结构:

@JsonIgnoreProperties(ignoreUnknown=true)
public class User{

    @JsonProperty("email")
    String email;

    MyWaypoint waypoints;

    public User(){}

    public User(String email){
        this.email = email;
    }

    public String getEmail(){return this.email; }
    public void setEmail(String _email){this.email = _email;}


    public MyWaypoint getWaypoints(){return waypoints;}
        public void setWaypoints(MyWaypoint points){ this.waypoints = points;}

    }

更新代码

用户

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyWaypoint {

    private double latitude;
    private double longitude;

    public MyWaypoint() {
    }
    public MyWaypoint(double latitude, double longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public double getLatitude() {
        return latitude;
    }
    public double getLongitude() {
        return longitude;
    }
}

经纬度POJO。

public class MapListActivityRealBack2 extends AppCompatActivity {

    private String LOG_TAG = "LOG_TAG";
    private Firebase mRef;
    private Firebase userRef;
    private String mUserId;

    FirebaseRecyclerAdapter<User, LatLngViewHolderBack2> mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        mRef = new Firebase(Constants.FIREBASE_URL);
        if (mRef.getAuth() == null) {
            loadLoginView();
        }


        try {
            mUserId = mRef.getAuth().getUid();
        } catch (Exception e) {
            loadLoginView();
        }


        final RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
        mRecyclerView.setHasFixedSize(false);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setReverseLayout(false);
        mRecyclerView.setLayoutManager(manager);


        // https://todoapprj.firebaseio.com/users/1a96a633-7e67-41b8-9aa7-c70d4b7eb59c
        final String userUrl = Constants.FIREBASE_URL + "/users/" + mUserId;
        userRef = new Firebase(userUrl);


        mAdapter = new FirebaseRecyclerAdapter<User, LatLngViewHolderBack2>(User.class, R.layout.list_item, LatLngViewHolderBack2.class, userRef) {
            @Override
            protected void populateViewHolder(final LatLngViewHolderBack2 latLngViewHolder, User item, final int i) {




                userRef.addValueEventListener(new ValueEventListener() {
                    List<MyWaypoint> userWayPointsList = new ArrayList<MyWaypoint>();

                    @Override
                    public void onDataChange(DataSnapshot wayPointsDataSnapshot) {
                        if(wayPointsDataSnapshot.getChildrenCount() > 0){
                            for (DataSnapshot wayPointsSnapshotChild : wayPointsDataSnapshot.getChildren()){
                                Log.i("FireBaseTester", "For-Loop :: wayPointsSnapshotChild.getValue() : "+wayPointsSnapshotChild.getValue());
                                if(wayPointsSnapshotChild.getChildrenCount()>0){

                                    for (DataSnapshot wayPointsChild : wayPointsSnapshotChild.getChildren()){
                                        //this is where we get the Lat and Lon
                                        double latitude = Double.parseDouble(wayPointsChild.child("latitude").getValue().toString());
                                        double longitude = Double.parseDouble(wayPointsChild.child("longitude").getValue().toString());
                                        userWayPointsList.add(new MyWaypoint( latitude,  longitude));
                                        Log.i("FireBaseTester","latitude = "+latitude+" , longitude = "+longitude);
                                    }
                                }

                            }
                        }
                        //here you can assign the points to the user
                        Log.i("FireBaseTester","There are "+userWayPointsList.size()+ " Points for User");
                    }

                    @Override
                    public void onCancelled(FirebaseError firebaseError) {
                        Log.e("FireBaseTester", "onCancelled - wayPointRef Error is " + firebaseError.getMessage());
                    }
                });
            }
        };

        mRecyclerView.setAdapter(mAdapter);

    }



    private void loadLoginView() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
}

我的活动

{{1}}
  

致命的例外:主要                                                                                      过程:com.example.rasmusjosefsson.rjcar,PID:19134                                                                                      com.firebase.client.FirebaseException:无法跳转到键入                                                                                          在com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:185)                                                                                          在   com.firebase.ui.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:161)                                                                                          在   com.firebase.ui.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:150)                                                                                          在   com.firebase.ui.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:190)                                                                                          在   android.support.v7.widget.RecyclerView $ Adapter.onBindViewHolder(RecyclerView.java:5471)                                                                                          在   android.support.v7.widget.RecyclerView $ Adapter.bindViewHolder(RecyclerView.java:5504)                                                                                          在   android.support.v7.widget.RecyclerView $ Recycler.getViewForPosition(RecyclerView.java:4741)                                                                                          在   android.support.v7.widget.RecyclerView $ Recycler.getViewForPosition(RecyclerView.java:4617)                                                                                          在   android.support.v7.widget.LinearLayoutManager $ LayoutState.next(LinearLayoutManager.java:1994)                                                                                          在   android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1390)                                                                                          在   android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353)                                                                                          在   android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574)                                                                                          在   android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028)                                                                                          在   android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2906)                                                                                          在   android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283)                                                                                          在android.view.View.layout(View.java:16630)                                                                                          在android.view.ViewGroup.layout(ViewGroup.java:5437)                                                                                          在   android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:122)                                                                                          在   android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)                                                                                          在   android.support.design.widget.AppBarLayout $ ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1170)                                                                                          在   android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:814)                                                                                          在android.view.View.layout(View.java:16630)                                                                                          在android.view.ViewGroup.layout(ViewGroup.java:5437)                                                                                          在android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)                                                                                          在android.widget.FrameLayout.onLayout(FrameLayout.java:273)                                                                                          在android.view.View.layout(View.java:16630)                                                                                          在android.view.ViewGroup.layout(ViewGroup.java:5437)                                                                                          在android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)                                                                                          在android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)                                                                                          在android.widget.LinearLayout.onLayout(LinearLayout.java:1495)                                                                                          在android.view.View.layout(View.java:16630)                                                                                          在android.view.ViewGroup.layout(ViewGroup.java:5437)                                                                                          在android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)                                                                                          在android.widget.FrameLayout.onLayout(FrameLayout.java:273)                                                                                          在android.view.View.layout(View.java:16630)                                                                                          在android.view.ViewGroup.layout(ViewGroup.java:5437)                                                                                          在android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)                                                                                          在android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)                                                                                          在android.widget.LinearLayout.onLayout(LinearLayout.java:1495)                                                                                          在android.view.View.layout(View.java:16630)                                                                                          在android.view.ViewGroup.layout(ViewGroup.java:5437)                                                                                          在android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)                                                                                          在android.widget.FrameLayout.onLayout(FrameLayout.java:273)                                                                                          在   com.android.internal.policy.PhoneWindow $ DecorView.onLayout(PhoneWindow.java:2678)                                                                                          在android.view.View.layout(View.java:16630)                                                                                          在android.view.ViewGroup.layout(ViewGroup.java:5437)                                                                                          在android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171)                                                                                          在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931)                                                                                          在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)                                                                                          在   android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:6013)                                                                                          在   android.view.Choreographer $ CallbackRecord.run(Choreographer.java:858)                                                                                          在android.view.Choreographer.doCallbacks(Choreographer.java:670)                                                                                          在android.view.Choreographer.doFrame(Choreographer.java:606)                                                                                          在   android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:844)                                                                                         在android.os.H

2 个答案:

答案 0 :(得分:0)

更新的答案 将您的Firebase网址更改为final String userUrl = Constants.FIREBASE_URL + "/users"(删除网址的其余部分)。 我在这个新代码中所做的是迭代数据并为每个lat-lon对创建MyWaypoint个实例。我已在代码中指出您可以开始使用MyWaypoint来做任何您想做的事情:

 userRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.i("FireBaseTester", "onDataChange()");
                if (dataSnapshot.getChildrenCount() > 0) {
                    Log.i("FireBaseTester", "There are "+dataSnapshot.getChildrenCount()+" Users");
                    for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                        String email = null;

                        if(userSnapshot.child("email") != null) {
                            //this is how you get the value of Email
                            email = userSnapshot.child("email").getValue().toString();
                            Log.i("FireBaseTester", "User Email:"+email+" PLAIN");
                        }
                        if(userSnapshot.child("waypoints") !=null){
                            if(userSnapshot.child("waypoints").getChildrenCount() > 0){
                                Firebase wayPointRef = userSnapshot.child("waypoints").getRef();

                                if(wayPointRef != null){
                                    wayPointRef.addValueEventListener(new ValueEventListener() {
                                        //this keeps per-user list of points
                                        List<MyWaypoint> userWayPointsList = new ArrayList<MyWaypoint>();
                                        @Override
                                        public void onDataChange(DataSnapshot wayPointsDataSnapshot) {
                                            if(wayPointsDataSnapshot.getChildrenCount() > 0){
                                                for (DataSnapshot wayPointsSnapshotChild : wayPointsDataSnapshot.getChildren()){
                                                    Log.i("FireBaseTester", "For-Loop :: wayPointsSnapshotChild.getValue() : "+wayPointsSnapshotChild.getValue());
                                                   if(wayPointsSnapshotChild.getChildrenCount()>0){

                                                       for (DataSnapshot wayPointsChild : wayPointsSnapshotChild.getChildren()){
                                                           //this is where we get the Lat and Lon
                                                           double latitude = Double.parseDouble(wayPointsChild.child("latitude").getValue().toString());
                                                           double longitude = Double.parseDouble(wayPointsChild.child("longitude").getValue().toString());
                                                           userWayPointsList.add(new MyWaypoint( latitude,  longitude));
                                                           Log.i("FireBaseTester","latitude = "+latitude+" , longitude = "+longitude);
                                                       }
                                                    }

                                                }
                                            }
                                            //here you can assign the points to the user
                                            Log.i("FireBaseTester","There are "+userWayPointsList.size()+ " Points for User");
                                        }

                                        @Override
                                        public void onCancelled(FirebaseError firebaseError) {
                                            Log.e("FireBaseTester", "onCancelled - wayPointRef Error is " + firebaseError.getMessage());
                                        }
                                    });
                                }
                            }
                            else{
                                Log.i("FireBaseTester", "No WayPoints Data Received");
                            }
                        }
                    }
                }
                else{
                    //no data?
                    Log.i("FireBaseTester", "No Data Received");
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                Log.e("FireBaseTester", "onCancelled - Error is "+firebaseError.getMessage());
            }
        });

最新更新: 您表示您更愿意检索特定于用户的数据而不是所有用户的列表(就像我在上面的代码中建议的那样)。以下是用户特定数据的代码。您的网址现在应该是:final String userUrl = Constants.FIREBASE_URL + "/users/" + mUserId;

userRef.myFirebaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {                
                if (dataSnapshot.getChildrenCount() > 0) {
                    Log.i("FireBaseTester", "There are "+dataSnapshot.getChildrenCount()+" User Attributes");
                        String email = null;
                        if(dataSnapshot.child("email") != null) {
                            //this is how you get the value of Email
                            email = dataSnapshot.child("email").getValue().toString();
                            Log.i("FireBaseTester", "User Email:"+email+" PLAIN");
                        }
                        if(dataSnapshot.child("waypoints") !=null){
                            if(dataSnapshot.child("waypoints").getChildrenCount() > 0){
                                Firebase wayPointRef = dataSnapshot.child("waypoints").getRef();

                                if(wayPointRef != null){
                                    wayPointRef.addValueEventListener(new ValueEventListener() {
                                        //this keeps per-user list of points
                                        List<MyWaypoint> userWayPointsList = new ArrayList<MyWaypoint>();
                                        @Override
                                        public void onDataChange(DataSnapshot wayPointsDataSnapshot) {
                                            if(wayPointsDataSnapshot.getChildrenCount() > 0){
                                                for (DataSnapshot wayPointsSnapshotChild : wayPointsDataSnapshot.getChildren()){
                                                    Log.i("FireBaseTester", "For-Loop :: wayPointsSnapshotChild.getValue() : "+wayPointsSnapshotChild.getValue());
                                                    if(wayPointsSnapshotChild.getChildrenCount()>0){

                                                        for (DataSnapshot wayPointsChild : wayPointsSnapshotChild.getChildren()){
                                                            //this is where we get the Lat and Lon
                                                            double latitude = Double.parseDouble(wayPointsChild.child("latitude").getValue().toString());
                                                            double longitude = Double.parseDouble(wayPointsChild.child("longitude").getValue().toString());
                                                            userWayPointsList.add(new MyWaypoint( latitude,  longitude));
                                                            Log.i("FireBaseTester","latitude = "+latitude+" , longitude = "+longitude);
                                                        }
                                                    }

                                                }
                                            }
                                            //here you can assign the points to the user
                                            Log.i("FireBaseTester","There are "+userWayPointsList.size()+ " Points for User");
                                        }

                                        @Override
                                        public void onCancelled(FirebaseError firebaseError) {
                                            Log.e("FireBaseTester", "onCancelled - wayPointRef Error is " + firebaseError.getMessage());
                                        }
                                    });
                                }
                            }
                            else{
                                Log.i("FireBaseTester", "No WayPoints Data Received");
                            }
                        }
                }
                else{
                    //no data?
                    Log.i("FireBaseTester", "No User Attributes");
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                Log.e("FireBaseTester", "onCancelled - Error is "+firebaseError.getMessage());
            }
        });

我希望这会让事情变得更轻松。顺便说一下,显示使用RecyclerView的代码非常有用 - 在这种情况下,您可能希望查看一个很好的示例here

答案 1 :(得分:0)

我发现工作的解决方案是使用List<List<String>>onDataChange()检索航点并将它们放入嵌套列表中。

此嵌套列表稍后在recyclerView中使用,其中嵌套列表中的每个列表代表&#34;查看项目&#34;在我的recyclerView

    private Firebase mRef;
    private Firebase mUserRef;
    private String mUserId;
    List<List<String>> latitudeNlongitude = new ArrayList<>();


    //  FirebaseRecyclerAdapter<MyLatLng123, LatLngViewHolderBack2> mAdapter;
    FirebaseRecyclerAdapter<MyWaypoint, LatLngViewHolderBack2> mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        mRef = new Firebase(Constants.FIREBASE_URL);
        if (mRef.getAuth() == null) {
            loadLoginView();
        }


        try {
            mUserId = mRef.getAuth().getUid();
        } catch (Exception e) {
            loadLoginView();
        }


        final RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
        mRecyclerView.setHasFixedSize(false);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setReverseLayout(false);
        mRecyclerView.setLayoutManager(manager);


        // https://todoapprj.firebaseio.com/users/1a96a633-7e67-41b8-9aa7-c70d4b7eb59c/waypoints
        final String userUrl = Constants.FIREBASE_URL + "/users/" + mUserId + "/waypoints";
        mUserRef = new Firebase(userUrl);


        if (mUserRef != null) {
            mUserRef.addValueEventListener(new ValueEventListener() {
                //this keeps per-user list of points
                List<MyWaypoint> userWayPointsList = new ArrayList<MyWaypoint>();

                @Override
                public void onDataChange(DataSnapshot wayPointsDataSnapshot) {
                    if (wayPointsDataSnapshot.getChildrenCount() > 0) {


                        for (DataSnapshot wayPointsSnapshotChild : wayPointsDataSnapshot.getChildren()) {
                            Log.i("FireBaseTester", "For-Loop :: wayPointsSnapshotChild.getValue() : " + wayPointsSnapshotChild.getValue());
                            if (wayPointsSnapshotChild.getChildrenCount() > 0) {


                                // Temporary list
                                List<String> latLngListTemp = new ArrayList<>();


                                for (DataSnapshot wayPointsChild : wayPointsSnapshotChild.getChildren()) {

                                    //this is where we get the Lat and Lon
                                    double latitude = Double.parseDouble(wayPointsChild.child("latitude").getValue().toString());
                                    double longitude = Double.parseDouble(wayPointsChild.child("longitude").getValue().toString());
                                    Log.i("FireBaseTester", "latitude = " + latitude + " , longitude = " + longitude);

                                    latLngListTemp.add(latitude + ", " + longitude);


                                }

                                // List containing a nested List<List<String>>
                                latitudeNlongitude.add(latLngListTemp);
                            }

                        }

                    }

                    //here you can assign the points to the user
                    Log.i("FireBaseTester", "There are " + userWayPointsList.size() + " Points for User");
                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {
                    Log.e("FireBaseTester", "onCancelled - wayPointRef Error is " + firebaseError.getMessage());
                }
            });
        } else {
            Log.i("FireBaseTester", "No WayPoints Data Received");
        }


        mAdapter = new FirebaseRecyclerAdapter<MyWaypoint, LatLngViewHolderBack2>(MyWaypoint.class, R.layout.list_item, LatLngViewHolderBack2.class, mUserRef) {
            @Override
            protected void populateViewHolder(final LatLngViewHolderBack2 latLngViewHolder, MyWaypoint item, final int i) {




                // Retrieves a List from the position (i) of the nested list at onDataChange --- > List<List<String>> latitudeNlongitude
                List<String> latlngListIterator = latitudeNlongitude.get(i);

                // New Empty list for each iteration
                List<String> latLngListTemporary  = new ArrayList<>();

                // Adding items to a new empty list for use in next method with googles api.
                for (String value : latlngListIterator) {
                    latLngListTemporary.add(value);
                }

                // Getting the start location and the endlocation
                String startLatLng = latLngListTemporary.get(0);
                String endLatLng = latLngListTemporary.get(latLngListTemporary .size() - 1);


                // Retrieves the information from googles API in JSON and turns them into POJOS