将firebase值与整数进行比较

时间:2018-03-28 13:46:17

标签: java android firebase firebase-realtime-database

我正在尝试将firebase数据与整数进行比较,但应用程序崩溃了。 这是代码:

 Firebase myfirebase; int result = 500;

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView mytextview = (TextView) findViewById(R.id.textView);
    Firebase.setAndroidContext(getApplicationContext());
    myfirebase = new Firebase("https://analog-85958.firebaseio.com/number");
    myfirebase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            String mychildtext = dataSnapshot.getValue(String.class);
            mytextview.setText(mychildtext);

            int num = Integer.parseInt(mychildtext);
            if (num == result)
            {
                Toast.makeText(getApplicationContext(),"success",Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(),"fail",Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

数据库结构:

enter image description here

1 个答案:

答案 0 :(得分:1)

您正在尝试获取String并且数据库中有一个int

  @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            String mychildtext = dataSnapshot.getValue(String.class); //here
            mytextview.setText(mychildtext);

            int num = Integer.parseInt(mychildtext); 

首先得到像这样的值

int mychildtext = Integer.valueOf(dataSnapShot.getValue().toString());

你也可以试试这个来获得价值

int mychildtext = dataSnapshot.getValue(Integer.class);

然后

mytextview.setText(mychildtext);

并且最后一部分在这里使用你的价值

int num = mychildtext;

     if (num == result)
                {
                    Toast.makeText(getApplicationContext(),"success",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(),"fail",Toast.LENGTH_SHORT).show();
                }

编辑:我认为您的引用是错误的,请改变它

String url = "https://analog-85958.firebaseio.com/number";
DatabaseReference ref = FirebaseDatabase.getInstance().getReferenceFromUrl(url);


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView mytextview = (TextView) findViewById(R.id.textView);
    Firebase.setAndroidContext(getApplicationContext());
    ref.addValueEventListener(new ValueEventListener() { ....   

希望它有所帮助,快乐编码