首先,我在论坛上看到了很多类似的问题,但没有人能够回答这个有效的问题。我尝试了一切。请帮忙。
我有一个arrayList,它从一个片段内的firebase数据库加载数据,但是在这一行listView.setAdapter(arrayAdapter);
上总是有一个空指针。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_my_account, container, false);
//chat rooms code///
listView = (ListView) v.findViewById(R.id.chatRoomsList);
/////added this check////
if(listView == null){
Log.d("mytag1","The listview is null");
}if(listView != null){
Log.d("mytag2","The listview is not null");
}
arrayAdapter = (new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1 , list_of_rooms));
listView.setAdapter(arrayAdapter);
add_room.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Map<String,Object> map = new HashMap<String, Object>();
map.put(room_name.getText().toString(),"");
DBRChatrooms.updateChildren(map);
}
});
DBRChatrooms.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()){
set.add(((DataSnapshot)i.next()).getKey());
}
list_of_rooms.clear();
list_of_rooms.addAll(set);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity().getApplicationContext(),ChatRoom.class);
intent.putExtra("room_name",((TextView)view).getText().toString() );
intent.putExtra("user_name",name);
startActivity(intent);
}
});
////////////////end of chat room code//////////////
//return view at the end
return v;
}
其余的:
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> list_of_rooms = new ArrayList<>();
private DatabaseReference DBRChatrooms = FirebaseDatabase.getInstance().getReference("Chatrooms");
阅读后我明白这是arrayAdapter中getActivity()
的问题。但我已经尝试过一切!!!
- 的getContext()
- 的getContext()。getApplicationContext()
- getActivity()。getApplicationContext()
- v.getContext / v.getActivity
- 等等,我尝试了10种不同的东西,总是空白
醇>
我甚至尝试将代码放入onActivity中创建并再次尝试所有内容仍然无效。
答案 0 :(得分:0)
我用错误的fragment_layout给inflater充气....感谢帮助,无论如何我一路上学到了一些东西