[英]Attempt to invoke Adapter.notifyDataSetChanged()' on a null object refernce
我也嘗試在onCreate()中添加適配器,它會引發空指針異常,並出現錯誤“嘗試在空對象引用上調用listVIew.setAdapter。
這是我在Main Activity中使用notifyDataSetChange()的代碼;
import static com.name.sample.Tab1.adapter;
public class Requests extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
Cursor c = myDB.rawQuery("SELECT * FROM requests", null);
int aIndex = c.getColumnIndex("name");
int bIndex = c.getColumnIndex("nick");
int cIndex = c.getColumnIndex("num");
name.clear();
nick.clear();
number.clear();
if (c.moveToFirst()){
do {
name.add(c.getString(aIndex));
nick.add(c.getString(bIndex));
number.add(c.getInt(cIndex));
} while (c.moveToNext());
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter.notifyDataSetChanged();
}
}
這是我的Tab1代碼這是適配器的代碼
public class Tab1 extends Fragment {
static ListView listNotifications;
final static ArrayList<String> name = new ArrayList<>();
static ArrayList<Integer> number = new ArrayList<>();
static ArrayList<String> nick = new ArrayList<>();
static ImageAdapter adapter;
public static class ImageAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ImageAdapter (Context context, String[] values) {
super(context, R.layout.list_with_icons, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_with_icons, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textViewName);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imagePicture);
textView.setText(values[position]);
// Change the icon for Windows and iPhone
return rowView;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1layout, container, false);
String[] nameString = new String[name.size()];
nameString = name.toArray(nameString);
adapter = new ImageAdapter (getActivity(), nameString);
listNotifications =(ListView)rootView.findViewById(R.id.listNotifications);
listNotifications.setAdapter(adapter);
return rootView;
}}
嘗試使用: adapterClass.this.notifyDataSetChanged()
中的onPostExcecute()
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
InvitedAdapter.this.notifyDataSetChanged();
}
您在列表視圖中添加了錯誤的適配器。 在onCreateView()中應該是這樣的:
listNotifications.setAdapter(adapter);
嘗試這個 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.