我已将此代码与json对象一起使用。现在我正在使用sqlite,并且它具有NPE错误。
Cursor newRes = myDb.getAllData();
while (newRes.moveToNext()) {
Product product = new Product(Integer.parseInt(newRes.getString(0).toString()), Integer.parseInt(newRes.getString(1).toString()), newRes.getString(2).toString(),
newRes.getString(3).toString(), newRes.getString(4).toString(), newRes.getString(5).toString(), Double.parseDouble(newRes.getString(6).toString()), newRes.getString(7).toString());
productTransList.add(product);
}
adapter = new ProductAdapter(mCtx, productTransList);
transRecyclerView.setAdapter(adapter);
编辑
07-13 09:05:29.763 13314-13351/com.example.arlene.capsmobile E/libdataflow_monitor: open error=Operation not permitted
07-13 09:05:31.542 13314-13314/com.example.arlene.capsmobile E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.arlene.capsmobile, PID: 13314
java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.example.arlene.capsmobile.translistTab.loadTransList(translistTab.java:135)
at com.example.arlene.capsmobile.translistTab.onCreate(translistTab.java:72)
错误productTransList.add(product);
答案 0 :(得分:2)
首先初始化productTransList,然后将对象添加到列表中。
productTransList = new ArrayList<>();
这将解决问题。
答案 1 :(得分:0)
在您的SQLiteHelper类中,您需要初始化列表:
public List<Product> getAllProducts() {
try {
List<Product > listProducts = new ArrayList<>();
String selectQuery = "SELECT * FROM " + dbSchema.table_name;
SQLiteDatabase mDb = this.getWritableDatabase();
Cursor cursor = mDb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Product product = new
Product(Integer.parseInt(cursor.getString(0).toString()),
Integer.parseInt(cursor.getString(1).toString()),
cursor.getString(2).toString(),
cursor.getString(3).toString(),
cursor.getString(4).toString(),
cursor.getString(5).toString(),
Double.parseDouble(cursor.getString(6).toString()),
cursor.getString(7).toString());
listProducts.add(mRecord);
} while (cursor.moveToNext());
}
return listProducts;
} catch (Exception ex) {
return null;
}
}
这里是SQLite的参考: SQLite Demo
在您的活动中,异步使用辅助方法getAllProducts并将空列表作为输入参数传递给它。
答案 2 :(得分:0)
首先初始化ArrayList
productTransList = new ArrayList<>();
Cursor newRes = myDb.getAllData();
while (newRes.moveToNext()) {
Product product = new Product(Integer.parseInt(newRes.getString(0).toString()), Integer.parseInt(newRes.getString(1).toString()), newRes.getString(2).toString(),
newRes.getString(3).toString(), newRes.getString(4).toString(), newRes.getString(5).toString(), Double.parseDouble(newRes.getString(6).toString()), newRes.getString(7).toString());
productTransList.add(product);
}
adapter = new ProductAdapter(mCtx, productTransList);
transRecyclerView.setAdapter(adapter);
希望这可能对您有帮助