如何使用sqlite数据库从数组中读取数据

时间:2018-02-01 13:13:47

标签: android sqlite android-recyclerview sqliteopenhelper

我想创建一个应用程序,我想使用sqlite数据库从数组中提取数据,下面给出了数组示例,有两个字符串和一个图像....数组中有很多项目我想要使用回收站视图以列表形式显示。

帮帮我怎么做。

这是我的代码:

public class NotificationAdapter extends RecyclerView.Adapter<NotificationDetailsHolder> {

    private List<NotificationHolder> notificationHolderList;

    public NotificationAdapter() {
        notificationHolderList = new ArrayList<>();

        notificationHolderList.add(new NotificationHolder("Name", "Details",R.drawable.image)
        ));  

    }

    @Override
    public NotificationDetailsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view=inflater.inflate(R.layout.abc_layout_workshop,parent,false);
        return new NotificationDetailsHolder(view);

    }

    @Override
    public void onBindViewHolder(NotificationDetailsHolder holder, int position) {

        NotificationHolder notificationHolder = notificationHolderList.get(position);
        holder.bindData(notificationHolder);
    }

    @Override
    public int getItemCount() {
        return notificationHolderList.size();
    }
}

1 个答案:

答案 0 :(得分:1)

首先,您必须将数据设置为pojo类。

活动代码:

 private void setData() {
        SQLiteDatabase db;

        ArrayList<LoadDataResult> cList = new ArrayList<LoadDataResult>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + Constants.TABLE_NAME;

        db = databaseHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                LoadDataResult product = new LoadDataResult();
                product.setName(cursor.getString(1));
                product.setSku(cursor.getString(2));
                product.setUpc(cursor.getString(3));
                product.setAssoc_upc(cursor.getString(4));
                product.setPrice(cursor.getString(5));
                product.setDisplaySize(cursor.getString(6));
                product.setDisplaySizeYes(Integer.parseInt(String.valueOf(cursor.getInt(7))));
                product.setStatus(cursor.getString(8));
                Log.e("DATASQL",""+cursor.getString(3));

                // Adding contact to list
                Constants.cList.add(product);
            } while (cursor.moveToNext());
          //  utils.hideDialog();
        }

}

将数据设置为pojo类后,ArrayListRecyclerAdapter发送到setAdapter类。

adapter = new TakeInventoryAdapter(TakeInventoryResult.this, cList);
            recyclerView.setAdapter(adapter);