当前位置: 首页 > 知识库问答 >
问题:

getValue()无法正确检索对象

欧阳炜
2023-03-14
{
  "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
  }
}
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());
            }
        });

我通过在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)
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个答案

鲜于宜修
2023-03-14

Firebase数据库命名约定更像是命名文件路径,例如访问您使用的游程。child(“rides”),而对于到达,它将是。child(“rides”)。child(“arrides”)或(rides/arrives)

从你发布的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更改监听器。

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();
    }
// ....
}
 类似资料:
  • 这是我的第二个版本,我试图从Firebase检索代码,并用它做一些事情。这是我的第二种方式: 这将崩溃,并出现错误代码: 未能将类型“__NSCFString”(0x10A77F4A0)的值强制转换为“NSDictionary”(0x10A780288)。在“更新”行。这是我的第一次尝试: 打印更多数据: -路径通道引用:可选(https://x.com/channels/-kegkajavh6u

  • 我有一个名为User的实体类,其中包含数据库的OneToMany列: 当我将用户插入数据库时,一切正常,他的汽车也被添加到user_cars表中。当检索汽车时,我得到这个异常: 我已经搜索了其他答案,但没有找到如何解决它。这就是我试图检索用户的方式。 问题是什么?我如何解决?我不明白后台发生了什么。

  • 我是Flink的新手,今天我遇到了一个奇怪的情况。 我运行Kafka服务器,然后使用confluent producer发送消息。使用consumer,我得到了正确的信息,但在应用程序中,我不能。我使用此图像设置message broker 我用这个向Kafka服务器发送消息 我发送的消息是 我用这个来听Kafka的留言 这是我的密码 当我将kafka源代码更改为KafkaSource时 user

  • 问题内容: 我有一个eclipse插件,它使用Jacob连接到COM组件。但是,在我完全关闭插件后,.exe文件仍然挂在Windows进程中。 我用于初始化,并确保在关闭应用程序之前为我创建的每个COM对象都调用了该对象,并在最后调用了该对象。 我是否遗漏了什么? 问题答案: TD2JIRA转换器也有同样的问题。最终必须修补Jacob文件之一才能释放对象。之后,一切顺利。 我的客户端logout(

  • GSON不是在一开始就解析我传递的整个JSON字符串吗?因此,最终,我希望新的数据源是对象。那可行吗?

  • 我得到了一个奇怪的问题与我的快照,其中用户名和电子邮件被获取,但我的快照返回零的个人资料图片。 快照正在工作,profileUrl确实显示了数据,所以我不知道可能是什么问题。下面是print(profileImageUrl)显示的内容和快照