如何在片段中访问 SQLite 数据到 ListView
Posted
技术标签:
【中文标题】如何在片段中访问 SQLite 数据到 ListView【英文标题】:How to access sqlite data to ListView in fragment 【发布时间】:2019-12-12 11:04:23 【问题描述】:我的 android 应用程序应该将 file.xlsx 保存到 sqlite DB 中,这个 DB 在启动时应该是空的,然后我从目录中选择 file.xlsx 将它保存到 sqlite 中,这是代码:
HomeFragment
public class HomeFragment extends Fragment
public ListView mainListView;
public XlsxDB xlsxDB;
public Intent fileintent;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
View parentView = inflater.inflate(R.layout.home, container, false);
mainListView = parentView.findViewById(R.id.listveiw);
FloatingActionButton btnImport = parentView.findViewById(R.id.btnImport);
btnImport.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("*/*");
startActivityForResult(fileintent, 10);
);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
LinearLayout linearLayoutParent = (LinearLayout) arg1;
LinearLayout lvh = (LinearLayout) linearLayoutParent.getChildAt(0);
TextView itemCode = (TextView) lvh.getChildAt(0);
TextView product = (TextView) lvh.getChildAt(1);
Bundle dataBundle = new Bundle();
dataBundle.putString("Item_Code", String.valueOf(itemCode.getText().toString()));
dataBundle.putString("Product", String.valueOf(product.getText().toString()));
Intent intent = new Intent(getApplicationContext(), ItemInfo.class);
intent.putExtras(dataBundle);
startActivity(intent);
);
ArrayList<HashMap<String, String>> myList;
myList = xlsxDB.getProducts();
if (myList.size() != 0)
ListAdapter adapter = new SimpleAdapter(getActivity(), myList,
R.layout.v, new String[]Item_Code, Product, Quantity,
new int[]R.id.TxtProductCode, R.id.txtproductname, R.id.TxtProductQty);
mainListView.setAdapter(adapter);
else
Toast.makeText(getContext(),"Kindly inform their is no data...",Toast.LENGTH_SHORT).show();
return parentView;
public void onActivityResult(int requestCode, int resultCode, Intent data)
switch (requestCode)
case 10:
if (resultCode == RESULT_OK)
FileInputStream inStream;
XSSFWorkbook wb = null;
try
inStream = (FileInputStream) getContext().getContentResolver().openInputStream(data.getData());
if (inStream != null)
wb = new XSSFWorkbook(inStream);
if (inStream != null)
inStream.close();
catch (IOException e)
Toast.makeText(getApplicationContext(), "kindly inform: " + e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
XlsxDB dbAdapter = new XlsxDB(getContext());
XSSFSheet sheet = null;
if (wb != null)
sheet = wb.getSheetAt(0);
if (sheet == null)
return;
dbAdapter.open();
dbAdapter.delete();
dbAdapter.insertExcelToSqlite(dbAdapter, sheet);
dbAdapter.close();
break;
ArrayList<HashMap<String, String>> myList;
myList = xlsxDB.getProducts();
if (myList.size() != 0)
ListAdapter adapter = new SimpleAdapter(getActivity(), myList,
R.layout.v, new String[]Item_Code, Product, Quantity,
new int[]R.id.TxtProductCode, R.id.txtproductname, R.id.TxtProductQty);
mainListView.setAdapter(adapter);
else
Toast.makeText(getContext(),"Kindly inform their is no data...",Toast.LENGTH_SHORT).show();
这是我的 sqlite 类:
XlsxDB
public class XlsxDB
private static final String Tablename = "MyTable1";
public static final String id = "_id";// 0 integer
public static final String Item_Code = "itemCode";
public static final String Product = "DescTxt";
public static final String Quantity = "Qty";
private SQLiteDatabase db;
private DBHelper dbHelper;
public XlsxDB(Context context)
dbHelper = new DBHelper(context);
public void open()
if (null == db || !db.isOpen())
try
db = dbHelper.getWritableDatabase();
catch (SQLiteException ignored)
public void close()
if (db != null)
db.close();
int insert(ContentValues values)
return (int) db.insert("MyTable1", null, values);
public void delete()
db = dbHelper.getWritableDatabase();
db.execSQL("delete from " + Tablename);
private class DBHelper extends SQLiteOpenHelper
private static final int VERSION = 1;
private static final String DB_NAME = "MyDB1.db";
DBHelper(Context context)
super(context, DB_NAME, null, VERSION);
@Override
public void onCreate(SQLiteDatabase db)
String create_sql = "CREATE TABLE IF NOT EXISTS "
+ Tablename + '(' + id
+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Item_Code + " TEXT ,"
+ Product + " TEXT ,"
+ Quantity + ", TEXT " + ')';
db.execSQL(create_sql);
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
db.execSQL("DROP TABLE IF EXISTS " + Tablename);
public static void insertExcelToSqlite(XlsxDB dbAdapter, Sheet sheet)
for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext(); )
Row row = rit.next();
ContentValues contentValues = new ContentValues();
row.getCell(0, Row.CREATE_NULL_AS_BLANK).setCellType(Cell.CELL_TYPE_STRING);
row.getCell(1, Row.CREATE_NULL_AS_BLANK).setCellType(Cell.CELL_TYPE_STRING);
row.getCell(2, Row.CREATE_NULL_AS_BLANK).setCellType(Cell.CELL_TYPE_STRING);
contentValues.put(XlsxDB.Item_Code, row.getCell(0, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
contentValues.put(XlsxDB.Product, row.getCell(1, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
contentValues.put(XlsxDB.Quantity, row.getCell(2, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
try
if (dbAdapter.insert(contentValues) < 0)
return;
catch (Exception ex)
Log.d("Exception in importing", ex.getMessage());
public ArrayList<HashMap<String, String>> getProducts()
ArrayList<HashMap<String, String>> proList;
proList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + Tablename;
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst())
do
HashMap<String, String> map = new HashMap<>();
map.put(Item_Code, cursor.getString(1));
map.put(Product, cursor.getString(2));
map.put(Quantity, cursor.getString(3));
proList.add(map);
while (cursor.moveToNext());
return proList;
但我得到了这个错误消息:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.example.testApp.Sqlite_DataBases.XlsxDB.getProducts()' on a null object reference
我试图替换
ArrayList<HashMap<String, String>> myList = xlsxDB.getProducts();
使用自定义适配器,但没有更多有用的结果
问题出在哪里
【问题讨论】:
【参考方案1】:您只是在 public XlsxDB xlsxDB;
中声明 xlsxDB,这会将 null 作为指向 xlsxDB 对象的指针(
因为不存在这样的对象)。
您需要使用xlsxDB = new XlsxDB(a_valid_context);
实例化/构造(实际)对象,以便变量具有指向实际对象的指针。
这可能会在片段的 onCreateView 中使用xlsxDB = new XlsxDB(getActivity());
完成
您不妨阅读What is a NullPointerException, and how do I fix it?
【讨论】:
以上是关于如何在片段中访问 SQLite 数据到 ListView的主要内容,如果未能解决你的问题,请参考以下文章
如何使用列表视图在选项卡式活动的片段中呈现 SQLite 表数据 [重复]