我正在活动中设置CRUD SQLite及其成功,但是当我尝试迁移到片段时,在放入数据时出现了一些错误
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
at com.example.wildangamin.pasarwildan.DaganganFragment.RefreshList(DaganganFragment.java:65)
at com.example.wildangamin.pasarwildan.BuatBiodata$1.onClick(BuatBiodata.java:52)
我尝试了一些东西,但没有一个起作用
有代码(DaganganFragment)
public void RefreshList() {
db = dbcenter.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM biodata", null);
daftar = new String[cursor.getCount()];
cursor.moveToFirst();
for (int cc = 0; cc < cursor.getCount(); cc++) {
cursor.moveToPosition(cc);
daftar[cc] = cursor.getString(1).toString();
}
listView01.setAdapter(new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, daftar));
listView01.setSelected(true);
listView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
final String selection = daftar[arg2]; //.getItemAtPosition(arg2).toString();
final CharSequence[] dialogitem = {"Lihat Data", "Update Data", "Hapus Data"};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Pilihan");
builder.setItems(dialogitem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
Intent i = new Intent(mContext, LihatBiodata.class);
i.putExtra("nama", selection);
startActivity(i);
break;
case 1:
Intent in = new Intent(mContext, UpdateBiodata.class);
in.putExtra("nama", selection);
startActivity(in);
break;
case 2:
SQLiteDatabase db = dbcenter.getWritableDatabase();
db.execSQL("delete from biodata where namabarang = '" + selection + "'");
RefreshList();
break;
}
}
});
builder.create().show();
}
});
((ArrayAdapter) listView01.getAdapter()).notifyDataSetInvalidated();
}
和(BuatBiodata)
ton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("insert into biodata(kode, namabarang, harga, hargasatuan, deskripsi) values('" +
text1.getText().toString() + "','" +
text2.getText().toString() + "','" +
text3.getText().toString() + "','" +
text4.getText().toString() + "','" +
text5.getText().toString() + "')");
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
DaganganFragment.df.RefreshList();
finish();
}
});
当处于活动状态时,它可以很好地工作,但是在某些情况下,它不能工作
最佳答案
检查mContext
的值是否正确设置。那应该是问题所在。
编辑:我检查了本教程中DaganganFragment
的实现。您正在访问对象df而不进行初始化。