Firebase列表适配器:错误“空对象引用”

时间:2018-06-01 20:35:21

标签: android firebase

我正在尝试学习使用firebase,但是当尝试在listView中加载数据时,应用程序会返回错误:

  

java.lang.RuntimeException:无法启动活动ComponentInfo {my activity} java.lang.NullPointerException:尝试在上调用虚方法'void com.firebase.ui.database.FirebaseListAdapter.startListening()' null对象引用。

如果有人能看到问题,那将非常有帮助。

我的数据库方面:

location
   40434734
      latitude: 40.434734
      longitude: -3.70701
      txt: "test"

我的课程:

public class start extends AppCompatActivity{

ListView lv;

FirebaseListAdapter adapter;

@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
    super.onCreate(savedInstanceState, persistentState);

    lv = (ListView) findViewById(R.id.listView);
    Query query = FirebaseDatabase.getInstance().getReference().child("location");

    FirebaseListOptions<LocationData> options = new FirebaseListOptions.Builder<LocationData>()
            .setLayout(R.layout.list_location)
            .setQuery(query,LocationData.class)
            .build();
    adapter = new FirebaseListAdapter(options) {
        @Override
        protected void populateView(View v, Object model, int position) {
            TextView stdID = v.findViewById(R.id.nombre);
            LocationData  ld = (LocationData) model;
            stdID.setText(ld.getTxt().toString());
        }
    };
    lv.setAdapter(adapter);

}

@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}

}

我的LocationData类来创建对象:

public class LocationData {

double latitude;
double longitude;
String txt;

public LocationData(){

}
public LocationData(double latitude, double longitude, String txt) {
    this.latitude = latitude;
    this.longitude = longitude;
    this.txt = txt;
}
public String getTxt() {
    return txt;
}

public void setTxt(String txt) {
    this.txt = txt;
}

public double getLatitude() {
    return latitude;
}

public void setLatitude(double latitude) {
    this.latitude = latitude;
}

public double getLongitude() {
    return longitude;
}

public void setLongitude(double longitude) {
    this.longitude = longitude;
}

2 个答案:

答案 0 :(得分:0)

而不是这个

adapter.startListening();

&安培;

adapter.stopListening();

你可以做 -

FirebaseListOptions<LocationData> options = new FirebaseListOptions.Builder<LocationData>()
        .setLayout(R.layout.list_location)
        .setQuery(query,LocationData.class)
        .setLifecycleOwner(this) 
        .build();

答案 1 :(得分:0)

  

com.firebase.ui.database.FirebaseListAdapter.startListening()'on a   null对象引用。

告诉你没有适配器设置为startListening,所以

只需更改此

FirebaseListAdapter adapter;

到这个

FirebaseListAdapter<LocationData> adapter;

由于您以错误的方式创建适配器,执行此操作将允许您填充它。

其余代码没问题,因为文档说明了