【问题标题】:Want to read data from firebase but get error想从 firebase 读取数据但出错
【发布时间】:2019-01-10 20:12:40
【问题描述】:

我想让我的应用程序读取这些始终在变化的数据。我在youtube上尝试了教程,打开应用程序时出错。

我想要获取到 android 应用的示例数据:

对于代码,我试过了

package com.example.dell.smarthouse;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

public class MenuTegangan extends AppCompatActivity {

    private TextView mtegangan1;
private DatabaseReference myRef;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_tegangan);
        mtegangan1 = (TextView) findViewById(R.id.tegangan1);
        myRef.child("Tegangan 1").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                String value = dataSnapshot.getValue(String.class);
                mtegangan1.setText(value);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                //Log.w(TAG, "Failed to read value.", error.toException());
            }
        });

    }
    }

关于修复此代码的任何提示?

【问题讨论】:

  • 运行此代码时遇到什么错误?

标签: android firebase firebase-realtime-database


【解决方案1】:

这里的问题是myref 有空指针对吗?这是因为你忘了初始化它。试试这个

FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference("Tegangan 1");
myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            String value = dataSnapshot.getValue(String.class);
            mtegangan1.setText(value);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            //Log.w(TAG, "Failed to read value.", error.toException());
        }
    });

希望这会有所帮助。干杯!

【讨论】:

    【解决方案2】:

    实际上,您还没有发布错误日志,所以我们无法解决具体错误,但原因之一是您在没有初始化的情况下访问myRef,所以它会产生 NullPointerException,所以请在访问之前初始化对象,如下所示

    myRef = FirebaseDatabase.getInstance();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-14
      • 2023-02-23
      • 1970-01-01
      • 2018-11-16
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多