我試圖創建一個與firebase聊天,試圖讓添加的用戶朋友ListView,但是當我把.setAdapter(),它說我有一個Java。 .setAdapter行上的lang.NullPointerException。Android ArrayAdapter NullPointerException(但不爲空)
package studio.brunocasamassa.superchat.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.firebase.database.DatabaseReference;
import java.util.ArrayList;
import studio.brunocasamassa.superchat.R;
import static android.R.layout.activity_list_item;
import static android.R.layout.simple_list_item_2;
/**
* A simple {@link Fragment} subclass.
*/
public class ContatosFragment extends Fragment {
private ListView listview_nomes;
private ArrayList<String> arraylist_nomes;
private ArrayAdapter<String> adapter_nomes = null;
private DatabaseReference firebaseDatabase;
public ContatosFragment() {
// Required empty public constructor
}
public String insertContact(String nomeContato) {
arraylist_nomes = new ArrayList<String>();
arraylist_nomes.add(nomeContato);
adapter_nomes = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_list_item_2,
android.R.id.text2,
arraylist_nomes);
return nomeContato;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (adapter_nomes == null) {
insertContact("teste");
}
listview_nomes = (ListView) getActivity().findViewById(R.id.ListContatos);
System.out.println(adapter_nomes);
> the problem:
listview_nomes.setAdapter(adapter_nomes);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_contatos, container, false);
}
}
我打電話insertContact methos在另一個類,如下所示:
Contato contato = new Contato();
contato.setidUser(idContact);
contato.setEmail(emailContact);
contato.setNome(usuarioContato.getNome());
ContatosFragment contact = new ContatosFragment();
contact.insertContact(usuarioContato.getNome());
System.out.println("nome usuario: "+usuarioContato.getNome());
我不知道如何解決它,如果有人知道, 感謝
已更新
我只是改變了我的insertContact方法(因爲這個問題看起來就像是它裏面一個ArrayAdapter變量):
public String insertContact(String nomeContato) {
arraylist_nomes = new ArrayList<String>();
arraylist_nomes.add(nomeContato);
System.out.println("nomes_array: " + arraylist_nomes);
adapter_nomes = new ArrayAdapter<String>(
getContext().getApplicationContext(),
android.R.layout.simple_list_item_2,
android.R.id.text2,
arraylist_nomes);
return nomeContato;
}
請發佈你的異常棧跟蹤。你的fragment.contatos.xml也可能有用。 –
你的'listview'爲空檢查下面的答案.. – rafsanahmad007