DataSnapshot.getValue()无法正确检索对象

时间:2017-08-28 12:29:45

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

我是firebase数据库和firebase的新手,我在尝试使用时遇到了一些问题。

我正在使用从firebase控制台导入的以下JSON代码,最初我刚刚在firebase控制台中创建了一个数据库结构,然后下载了JSON代码,它如下:

{
  "rides" : {
    "arrive" : "kech",
    "depart" : "agadir",
    "detail" : "0,1",
    "msg" : false,
    "phone" : true,
    "price" : 15,
    "profile_id" : 0,
    "spots" : 3,
    "timedate" : "11/12/2017 11:15",
    "vocal_id" : 0
  }
}

我想要获取的对象名为 Ride.java

public class Ride {
    private String arrive;
    private String depart;
    private String detail;
    private boolean msg;
    private boolean phone;
    private int price;
    private int profile_id;
    private int spots;
    private String timedate;
    private int vocal_id;

    public Ride() {}

    // public getters (I created them I just didn't post it all to make the post shorter)
}

要使用以下代码收听我的数据库参考:

FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("rides").child("0"); // 0 is the ride id

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                    Ride ride = singleSnapshot.getValue(Ride.class);
                    rides.add(ride); // list of rides used later in a listadapter
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e(TAG, "onCancelled", databaseError.toException());
            }
        });

我试图从firebase db中获取一次,并在我的应用中显示它。在firebase控制台中,它有url: https://myapp.firebaseio.com/rides/0 (第二次骑行有id 1,依此类推)。抓住所有游乐设施并从每次游览中获取其属性的最佳做法是什么?

修改:当我删除.child("0")时,我没有收到任何错误,但 listView 中没有任何内容。显然rides.add(ride)由于某种原因没有发生。

我通过在addListenerForSingleValueEvent()方法之外添加一个简单的 Ride 实例来测试它,它运行正常。

我也尝试将监听器更改为addValueEventListener(),结果相同..

Edit2:当我尝试从数据库中检索整数时收到错误消息。

我在数据库监听器中尝试了这个:

public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot singleSnapshot: dataSnapshot.getChildren()) {
                    int price = (int) singleSnapshot.child("price").getValue(); //  error takes place here
                    Log.d("FirebaseDb", String.valueOf(price));
                }
            }

结果是这个错误:(包含所有整数)

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
    at com.ride.ive.anas.iveride.Fragments.RidesFragment$1.onDataChange(RidesFragment.java:96)

但是当我检索String或Boolean时,它可以正常工作,如:

String arrive = (String) singleSnapshot.child("arrive").getValue();

Boolean usePhone = (Boolean) singleSnapshot.child("phone").getValue();

Edit3:根据@Prodigy的要求,这是 RidesFragment.java 文件。 其中我有一个ListView,我尝试显示存储在我的firebase数据库中的所有Ride实例。

public class RidesFragment extends Fragment {

    ListView list;
    RidesAdapter2 ridesAdapter;
    List<Ride> rides;
    Ride ride;

    List<RidePojo> filteredRides;
    LinearLayout layoutFilter;
    boolean filtersVisible = false;
    boolean searchDone = false;

    String userNumber;

    public RidesFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_rides, container, false);
        getActivity().setTitle("Search for a ride:");

        // filter action button stuff
        setHasOptionsMenu(true);
        layoutFilter = rootView.findViewById(R.id.ll_filter_screen);

        /*FragmentManager fm = getActivity().getSupportFragmentManager();
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);*/

        ridesAdapter = new RidesAdapter2(getContext(), rides);


        Bundle arguments = getArguments();
        list = rootView.findViewById(R.id.rides_list);
        rides = new ArrayList<>();

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("rides");

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot singleSnapshot: dataSnapshot.getChildren()) {
                    Ride ride = singleSnapshot.getValue(Ride.class);
                    rides.add(ride);
                    ridesAdapter.notifyDataSetChanged();
                    Log.d("FbDatabase", singleSnapshot.toString());
                }

            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e(TAG, "onCancelled", databaseError.toException());
            }
        });

        rides.add(ride);

        // In case the rides ArrayList is not empty another fragment appears for no rides criteria
        if(rides.isEmpty()) {
            rootView = inflater.inflate(R.layout.fragment_empty, container, false);
            Button rideButton = rootView.findViewById(R.id.btn_post_ride);
            Button requestButton = rootView.findViewById(R.id.btn_post_request);

            rideButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    launchFragment(new OfferRideFragment(), getActivity());
                }
            });

            requestButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    launchFragment(new RequestFragment(), getActivity());
                }
            });

        }
        else {
            list.setAdapter(ridesAdapter);

        }
        return rootView;
    }

    protected void launchFragment(Fragment f, FragmentActivity a) {
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                a.getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, f);
        fragmentTransaction.commit();
    }
// ....
}

1 个答案:

答案 0 :(得分:1)

Firebase数据库命名约定更像是命名文件路径,例如访问你使用的游乐设施.child(“rides”),而到达时它将是.child(“rides”)。child(“到达”)或(游乐设施) /到达)

从你发布的firebase链接我可以看到你有一个节点乘坐子节点0等.... 但是你发布的json看不到节点“0”,这肯定会引发错误。

The correct Json should be 
{
  "rides" : {
   "0": {
    "arrive" : "kech",
    "depart" : "agadir",
    "detail" : "0,1",
    "msg" : false,
    "phone" : true,
    "price" : 15,
    "profile_id" : 0,
    "spots" : 3,
    "timedate" : "11/12/2017 11:15",
    "vocal_id" : 0
}
  }
}

这将提取您需要的数据,并且不要忘记在添加数据时在tour list adapter上添加notifydata change listener。

请参阅下面的编辑代码

public class RidesFragment extends Fragment {

    ListView list;
    RidesAdapter2 ridesAdapter;
    List<Ride> rides;
    Ride ride;

    List<RidePojo> filteredRides;
    LinearLayout layoutFilter;
    boolean filtersVisible = false;
    boolean searchDone = false;

    String userNumber;

    public RidesFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_rides, container, false);
        getActivity().setTitle("Search for a ride:");

        // filter action button stuff
        setHasOptionsMenu(true);
        layoutFilter = rootView.findViewById(R.id.ll_filter_screen);

        /*FragmentManager fm = getActivity().getSupportFragmentManager();
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);*/




        Bundle arguments = getArguments();
        list = rootView.findViewById(R.id.rides_list);
        rides = new ArrayList<>();
        ridesAdapter = new RidesAdapter2(getContext(), rides);
        list.setAdapter(ridesAdapter);

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("rides");

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot singleSnapshot: dataSnapshot.getChildren()) {
                    Ride ride = singleSnapshot.getValue(Ride.class);
                    rides.add(ride);
                    ridesAdapter.notifyDataSetChanged();
                    Log.d("FbDatabase", singleSnapshot.toString());
                }

            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e(TAG, "onCancelled", databaseError.toException());
            }
        });

        //rides.add(ride);

        // In case the rides ArrayList is not empty another fragment appears for no rides criteria
        if(rides.isEmpty()) {
            rootView = inflater.inflate(R.layout.fragment_empty, container, false);
            Button rideButton = rootView.findViewById(R.id.btn_post_ride);
            Button requestButton = rootView.findViewById(R.id.btn_post_request);

            rideButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    launchFragment(new OfferRideFragment(), getActivity());
                }
            });

            requestButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    launchFragment(new RequestFragment(), getActivity());
                }
            });

        }

        //else {
            //list.setAdapter(ridesAdapter);

        //}
        return rootView;
    }

    protected void launchFragment(Fragment f, FragmentActivity a) {
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                a.getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, f);
        fragmentTransaction.commit();
    }
// ....
}