我正在使用 firebase 數據庫,想要在列表視圖中顯示數據。當我調用 firebase 數據庫的 onDataChange() 時,它顯示空指針異常。我在谷歌和許多其他網站上找到了最好的方法,但沒有任何東西可以幫助我擺脫這個錯誤,所以請幫助我,我在過去三個小時內陷入了這個錯誤......這是名為 Articles_from_firebase.java 的 Mainactiviy:public class Articles_from_fireabse extends AppCompatActivity {EditText editTextName;Spinner spinnerGenre;Button buttonAddArtist;ListView listViewArtists;DatabaseReference databaseArtists;//a list to store all the artist from firebase databaseList<Artist> artists;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_articles_from_fireabse); databaseArtists = FirebaseDatabase.getInstance().getReference("artists"); editTextName = (EditText) findViewById(R.id.editTextName); spinnerGenre = (Spinner) findViewById(R.id.spinnerGenres); listViewArtists = (ListView) findViewById(R.id.listViewArtists); buttonAddArtist = (Button) findViewById(R.id.buttonAddArtist); buttonAddArtist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //calling the method addArtist() //the method is defined below //this method is actually performing the write operation addArtist(); } });}private void addArtist() { //getting the values to save String name = editTextName.getText().toString().trim(); String genre = spinnerGenre.getSelectedItem().toString(); //checking if the value is provided if (!TextUtils.isEmpty(name)) { //getting a unique id using push().getKey() method //it will create a unique id and we will use it as the Primary Key for our Artist String id = databaseArtists.push().getKey(); //creating an Artist Object Artist artist = new Artist(id, name, genre); }}
2 回答

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
簡單的解決方案
每當您調用artists.clear();
檢查以確保它不為空時。
if(artists != null) artists.clear(); else artists = new ArrayList<>();
可持續解決方案
你應該考慮對象 arry 的作用artists
是什么。在本例中,您有一個數據庫和一個數組,它們都存儲有關藝術家的信息。數據庫應該存儲持久數據,即程序執行后仍存在的數據。然而,您的artists
對象在運行時就存在。
因此,您應該在程序開始處編寫代碼,將數據從數據庫加載到對象中artists
。在運行時引用/編輯/添加到artist
對象。最后,在運行時結束時使用清理代碼來更新數據庫中的藝術家表。
添加回答
舉報
0/150
提交
取消