我已經嘗試在onCreate()中添加適配器,並且它引發了一個空指針異常,錯誤爲'嘗試調用null上的listVIew.setAdapter對象引用。嘗試在空對象上調用Adapter.notifyDataSetChanged()'參考
這裏是我在我的主要活動中使用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;
}}
我用它作爲Tab1.InvitedAdapter.this.notifyDataSetChanged();它給出了一個錯誤,它不是可以使用的封閉類 –
:'Tab1.InvitedAdapter.notifyDataSetChanged();' – rafsanahmad007
notifyDataSetChanged();不能從靜態上下文中引用。是的,我也將適配器更改爲非靜態。 –