我正在使用 firebase 數(shù)據(jù)庫,想要在列表視圖中顯示數(shù)據(jù)。當(dāng)我調(diào)用 firebase 數(shù)據(jù)庫的 onDataChange() 時,它顯示空指針異常。我在谷歌和許多其他網(wǎng)站上找到了最好的方法,但沒有任何東西可以幫助我擺脫這個錯誤,所以請幫助我,我在過去三個小時內(nèi)陷入了這個錯誤......這是名為 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貢獻(xiàn)1801條經(jīng)驗 獲得超8個贊
簡單的解決方案
每當(dāng)您調(diào)用artists.clear();
檢查以確保它不為空時。
if(artists != null) artists.clear(); else artists = new ArrayList<>();
可持續(xù)解決方案
你應(yīng)該考慮對象 arry 的作用artists
是什么。在本例中,您有一個數(shù)據(jù)庫和一個數(shù)組,它們都存儲有關(guān)藝術(shù)家的信息。數(shù)據(jù)庫應(yīng)該存儲持久數(shù)據(jù),即程序執(zhí)行后仍存在的數(shù)據(jù)。然而,您的artists
對象在運(yùn)行時就存在。
因此,您應(yīng)該在程序開始處編寫代碼,將數(shù)據(jù)從數(shù)據(jù)庫加載到對象中artists
。在運(yùn)行時引用/編輯/添加到artist
對象。最后,在運(yùn)行時結(jié)束時使用清理代碼來更新數(shù)據(jù)庫中的藝術(shù)家表。

慕斯709654
TA貢獻(xiàn)1840條經(jīng)驗 獲得超5個贊
yes 初始化列表藝術(shù)家;在 onCreate(){} 內(nèi)部
像這樣的 Artists = new ArrayList<>();
添加回答
舉報
0/150
提交
取消