空指针异常:尝试调用虚方法'void

时间:2017-07-02 18:06:33

标签: android listview firebase android-adapter

我的代码有问题。我正在学习如何使用Android创建Simple Firebase CRUD应用程序。这是我的MainActivity代码:

package com.ogigpermana.crudfirebaseapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

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.ValueEventListener;
import com.ogigpermana.crudfirebaseapp.adapter.ArtistList;
import com.ogigpermana.crudfirebaseapp.model.Artist;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    EditText editTextName;
    Button buttonAdd;
    Spinner spinnerGenres;

    DatabaseReference databaseArtists;
    ListView listViewArtists;
    List<Artist> artistList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        databaseArtists = FirebaseDatabase.getInstance().getReference("artists");

        editTextName = (EditText) findViewById(R.id.editTextName);
        buttonAdd = (Button) findViewById(R.id.buttonAddArtist);
        spinnerGenres = (Spinner) findViewById(R.id.spinnerGenres);

        listViewArtists = (ListView) findViewById(R.id.listViewArtists);

        artistList = new ArrayList<>();

        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addArtist();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        databaseArtists.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                artistList.clear();

                for (DataSnapshot artistSnapshot: dataSnapshot.getChildren()){
                    Artist artist = artistSnapshot.getValue(Artist.class);

                    artistList.add(artist);
                }

                ArtistList adapter = new ArtistList(MainActivity.this, artistList);

                listViewArtists.setAdapter(adapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void addArtist(){
        String name = editTextName.getText().toString().trim();
        String genre = spinnerGenres.getSelectedItem().toString();

        if (!TextUtils.isEmpty(name)){

            String id  = databaseArtists.push().getKey();

            Artist artist = new Artist(id, name, genre);

            databaseArtists.child(id).setValue(artist);

            Toast.makeText(this, "Artis berhasil ditambah", Toast.LENGTH_LONG).show();

        }else{
            Toast.makeText(this, "Nama tidak boleh kosong", Toast.LENGTH_LONG).show();
        }
    }
}

以下是我运行时显示的错误代码:

  

07-03 00:30:45.727 30907-30907 / com.ogigpermana.crudfirebaseapp   E / AndroidRuntime:致命异常:主要

                                                                                   过程:com.ogigpermana.crudfirebaseapp,PID:30907

                                                                                   java.lang.NullPointerException:尝试调用虚方法'void   android.widget.ListView.setAdapter(android.widget.ListAdapter)'上的一个   null对象引用                                                                                        在   com.ogigpermana.crudfirebaseapp.MainActivity $ 2.onDataChange(MainActivity.java:72)                                                                                        在com.google.android.gms.internal.zzbmz.zza(未知来源)                                                                                        在com.google.android.gms.internal.zzbnz.zzYj(未知来源)                                                                                        在com.google.android.gms.internal.zzboc $ 1.run(未知来源)                                                                                        在android.os.Handler.handleCallback(Handler.java:739)                                                                                        在android.os.Handler.dispatchMessage(Handler.java:95)                                                                                        在android.os.Looper.loop(Looper.java:148)                                                                                        在android.app.ActivityThread.main(ActivityThread.java:5441)                                                                                        at java.lang.reflect.Method.invoke(Native Method)                                                                                        在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:738)                                                                                        在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

2 个答案:

答案 0 :(得分:1)

试试这个 -

ListView

中交叉检查您的activity_main.xml ID

答案 1 :(得分:0)

首先,我认为你不应该在回调中创建一个新的适配器。这是一个糟糕的设计。您可以在更改数据时通知适配器。 我认为问题是你可能会在收到意见之前收到回电,例如: G。在配置更改期间(如设备轮换)。

您应该了解生命周期。有些技术可以让它更容易像LiveData

总结一下:不要在回调中创建新的适配器。使用notifyDataSetChanged()更改数据并通知适配器。不要忘记在拆除活动/片段期间取消注册侦听器并检查是否存在视图。