簡體   English   中英

android:從列表中將數據存儲在Sqlite中<HashMap>

[英]android:Store data in Sqlite from List<HashMap>

在我的項目中有一個類別列表,每個類別都有多個項目。我想將這些類別與其多個項目一起存儲。我的問題是我可以將其存儲在sqlite中並希望在回收視圖中對其進行檢索。

[![在屏幕快照中,每個類別均具有選擇編號。我想將其插入具有多個項目的類別,並且也要按照屏幕快照中的顯示進行顯示] [1]] [1]

[1]: https ://i.stack.imgur.com/9WaKm.png`公共類ViewAllAdapter擴展了RecyclerView.Adapter {

private ArrayList<StringMenuListBean> dataList;
private Context mContext;
private TextView itemText;
private List<String> itemList;

public ViewAllAdapter(Context context, ArrayList<StringMenuListBean> dataList) {
    this.dataList = dataList;
    this.mContext = context;
}


@Override
public ItemRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowitem_viewall, null);
    v.setLayoutParams(new RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.MATCH_PARENT,
            RecyclerView.LayoutParams.WRAP_CONTENT
    ));
    ItemRowHolder mh = new ItemRowHolder(v, mContext);
    return mh;

}

@Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int position) {

    itemList = new ArrayList<>();
    final StringMenuListBean model = dataList.get(position);
    String str = model.getName();
    String category = str.substring(0, str.indexOf("-"));
    String item = str.substring(str.indexOf("-") + 1, str.length());
    itemList.add(item);

    itemRowHolder.linear.removeAllViews();
    LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
    llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);

    Log.e("category", category);
    Log.e("remainder", item);
    itemRowHolder.tv_category_item.setText(category + " :");

    for (int k = 0; k < itemList.size(); k++) {

        itemText = new TextView(mContext);
        itemText.setText((position + 1) + " ." + item);
        itemText.setTextColor(Color.parseColor("#43A047"));
        itemText.setLayoutParams(llp);
        itemRowHolder.linear.addView(itemText);

    }


}

@Override
public int getItemCount() {
    return (null != dataList ? dataList.size() : 0);
}


public class ItemRowHolder extends RecyclerView.ViewHolder {

    protected TextView tv_category_item;
    protected LinearLayout linear;


    public ItemRowHolder(View view, final Context mContextv) {
        super(view);

        tv_category_item = (TextView) view.findViewById(R.id.tv_category_item);
        linear = (LinearLayout) view.findViewById(R.id.linear);
    }

}

} here is my Activity公共類ViewAllActivity擴展了AppCompatActivity實現的View.OnClickListener {

RecyclerView viewall_recycleview;
ViewAllAdapter viewallAdapter;
TextView tv_ID;
TextView tv_PACKID;
TextView tv_PACKAGENAME;
TextView tv_USERID;
TextView tv_USER_NAME;
TextView tv_CATID;
TextView tv_CATNAME;
TextView tv_MENUITEMS;
TextView tv_MEMBER;
TextView tv_DATE;
TextView tv_TIME;
TextView tv_TOTAL_PRICE;
TextView tv_ORDER_TYPE;
TextView tv_DISCOUNT;
TextView tv_CITY;
TextView tv_PROMOCODE;
TextView tv_PAYMENT_STATUS;
TextView tv_PRICE;
TextView tv_MENUID;
TextView tv_SUBPACKAGENAME;
TextView tv_CURRENT_DATE;
Button btn_download;

MenuDetailBean menuDetailBean;
Bundle activitybundle;
String subpackage_id, pack_id;
String menuitem;
ArrayList<StringMenuListBean> stringMenuList;
StringMenuListBean stringMenu;
List<String> menulist;
List<String> arraylist1;
File imagePath;
RecyclerView rcyView_mymenu;

Bitmap bitmap;
View view;
ByteArrayOutputStream bytearrayoutputstream;
File file;
FileOutputStream fileoutputstream;
boolean boolean_save;
LinearLayout ll_linear;


MenuAdapter menuAdapter;

public static Bitmap loadBitmapFromView(View v, int width, int height) {
    Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
    v.draw(c);
    return b;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_viewall);

    init();
    setTextAndList();
    btn_download.setOnClickListener(this);


}

private void init() {
    activitybundle = getIntent().getExtras();

    pack_id = activitybundle.getString("pack_id");
    subpackage_id = activitybundle.getString("sub_package_id");

// Log.e(“ subpackage_id”,subpackage_id);

    bytearrayoutputstream = new ByteArrayOutputStream();


    rcyView_mymenu = (RecyclerView) findViewById(R.id.rcyView_mymenu);
    rcyView_mymenu.setNestedScrollingEnabled(false);

    tv_SUBPACKAGENAME = (TextView) findViewById(R.id.tv_SUBPACKAGENAME);
    tv_PRICE = (TextView) findViewById(R.id.tv_PRICE);
    tv_TOTAL_PRICE = (TextView) findViewById(R.id.tv_TOTAL_PRICE);
    tv_DATE = (TextView) findViewById(R.id.tv_DATE);
    tv_TIME = (TextView) findViewById(R.id.tv_TIME);
    tv_MEMBER = (TextView) findViewById(R.id.tv_MEMBER);
    tv_ORDER_TYPE = (TextView) findViewById(R.id.tv_ORDER_TYPE);
    btn_download = (Button) findViewById(R.id.btn_download);
    ll_linear = (LinearLayout) findViewById(R.id.ll_linear);


}

private void setTextAndList() {
    menuDetailBean = DbUtils.getMenuDetail(getApplicationContext(), pack_id);

    tv_SUBPACKAGENAME.setText(menuDetailBean.getSUBPACKAGE_NAME());
    tv_PRICE.setText(menuDetailBean.getPRICE() + "/-");
    tv_TOTAL_PRICE.setText(menuDetailBean.getTOTAL_PRICE() + "Rs.");
    tv_DATE.setText(menuDetailBean.getDATE());
    tv_TIME.setText(menuDetailBean.getTIME());
    tv_MEMBER.setText(menuDetailBean.getMEMBER());
    tv_ORDER_TYPE.setText(menuDetailBean.getORDER_TYPE());

    menuitem = menuDetailBean.getMENUITEMS();
    menulist = Arrays.asList(menuitem.split(","));
    Log.e("meuitem", "" + menulist.size());
    stringMenuList = new ArrayList<>();
    for (int i = 0; i < menulist.size(); i++) {
        StringMenuListBean stringMenu = new StringMenuListBean();
        stringMenu.setName(menulist.get(i));
        stringMenuList.add(stringMenu);
    }

    viewallAdapter = new ViewAllAdapter(getApplication(), stringMenuList);
    rcyView_mymenu.setHasFixedSize(true);
    rcyView_mymenu.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
    rcyView_mymenu.setAdapter(viewallAdapter);


}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_download:

            Bitmap bitmap1 = loadBitmapFromView(ll_linear, ll_linear.getWidth(), ll_linear.getHeight());
            saveBitmap(bitmap1);

            break;

    }

}

public void saveBitmap(Bitmap bitmap) {

    File imagePath = new File("/sdcard/screenshotdemo.jpg");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
        Toast.makeText(getApplicationContext(), imagePath.getAbsolutePath() + "", Toast.LENGTH_SHORT).show();
        boolean_save = true;

        btn_download.setText("Check image");

        Log.e("ImageSave", "Saveimage");
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}

} this is my Activity and below is my Database Utility code in which i saved all cart item . i want every added item is shown in different activity with its whole information. this is my Activity and below is my Database Utility code in which i saved all cart item . i want every added item is shown in different activity with its whole information. 公共類DbUtils {

public static void saveCart(Context context, CartItemBean data) {
    ContentValues value = new ContentValues();


    // for (CartItemBean data : data1) {
    value.put(DbConstants.COLUMN_PACKID, data.getCOLUMN_PACKID());
    value.put(DbConstants.COLUMN_PACKAGENAME, data.getCOLUMN_PACKAGENAME());
    value.put(DbConstants.COLUMN_SUBPACKAGEID, data.getCOLUMN_SUBPACKAGE_ID());
    value.put(DbConstants.COLUMN_SUBPACKAGENAME, data.getCOLUMN_SUBPACKAGE_NAME());
    value.put(DbConstants.COLUMN_USERID, data.getCOLUMN_USERID());
    value.put(DbConstants.COLUMN_USER_NAME, data.getCOLUMN_USER_NAME());
    value.put(DbConstants.COLUMN_CATID, data.getCOLUMN_CATID());
    value.put(DbConstants.COLUMN_CATNAME, data.getCOLUMN_CATNAME());
    value.put(DbConstants.COLUMN_MENUITEMS, data.getCOLUMN_MENUITEMS());
    value.put(DbConstants.COLUMN_MENUID, data.getCOLUMN_MENUID());
    value.put(DbConstants.COLUMN_MEMBER, data.getCOLUMN_MEMBER());
    value.put(DbConstants.COLUMN_DATE, data.getCOLUMN_DATE());
    value.put(DbConstants.COLUMN_TIME, data.getCOLUMN_TIME());
    value.put(DbConstants.COLUMN_TOTAL_PRICE, data.getCOLUMN_TOTAL_PRICE());
    value.put(DbConstants.COLUMN_ORDER_TYPE, data.getCOLUMN_ORDER_TYPE());
    value.put(DbConstants.COLUMN_DISCOUNT, data.getCOLUMN_DISCOUNT());
    value.put(DbConstants.COLUMN_CITY, data.getCOLUMN_CITY());
    value.put(DbConstants.COLUMN_CURRENTDATE, data.getCOLUMN_CURRENT_DATE());
    value.put(DbConstants.COLUMN_PRICE, data.getCOLUMN_PRICE());
    value.put(DbConstants.COLUMN_PROMOCODE, data.getCOLUMN_PROMOCODE());
    value.put(DbConstants.COLUMN_PAYMENT_STATUS, data.getCOLUMN_PAYMENT_STATUS());
    DbAccesser.getInstance(context).insertIntoTable(value,
            DbConstants.TABLE_CART);
    // }
}

// get product list
public static ArrayList<CartItemBean> getCartItems(Context context) {
    ArrayList<CartItemBean> offlineDataList = new ArrayList<CartItemBean>();
    Cursor cursor = DbAccesser.getInstance(context).query(DbConstants.TABLE_CART, null, null,
            null, null, null, null);


    if (cursor != null && cursor.moveToFirst()) {
        while (!cursor.isAfterLast()) {
            CartItemBean data = new CartItemBean();

            data.setCOLUMN_ID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_ID))));
            data.setCOLUMN_CATID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CATID))));
            data.setCOLUMN_PAYMENT_STATUS((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PAYMENT_STATUS))));
            data.setCOLUMN_USER_NAME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_USER_NAME)))));
            data.setCOLUMN_USERID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_USERID))));
            data.setCOLUMN_PACKAGENAME((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PACKAGENAME))));
            data.setCOLUMN_CATNAME((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CATNAME))));
            data.setCOLUMN_CITY((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CITY))));
            data.setCOLUMN_CURRENT_DATE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_CURRENTDATE))));
            data.setCOLUMN_DATE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_DATE))));
            data.setCOLUMN_DISCOUNT(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_DISCOUNT)))));
            data.setCOLUMN_MEMBER((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MEMBER))));
            data.setCOLUMN_MENUITEMS((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MENUITEMS))));
            data.setCOLUMN_ORDER_TYPE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_ORDER_TYPE))));
            data.setCOLUMN_PACKID((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PACKID))));
            data.setCOLUMN_PROMOCODE((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PROMOCODE))));
            data.setCOLUMN_TIME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_TIME)))));
            data.setCOLUMN_PRICE(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_PRICE)))));
            data.setCOLUMN_MENUID(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_MENUID)))));
            data.setCOLUMN_TOTAL_PRICE(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_TOTAL_PRICE)))));
            data.setCOLUMN_SUBPACKAGE_ID(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_SUBPACKAGEID)))));
            data.setCOLUMN_SUBPACKAGE_NAME(((cursor.getString(cursor.getColumnIndex(DbConstants.COLUMN_SUBPACKAGENAME)))));


            offlineDataList.add(data);
            cursor.moveToNext();
        }
    }
    return offlineDataList;
}


public static MenuDetailBean getMenuDetail(Context context, String packId) {

    DbHelper dbHelper = new DbHelper(context);
    SQLiteDatabase database;
    database = dbHelper.getReadableDatabase();

    String selectQuery = "SELECT  * FROM " + DbConstants.TABLE_CART + " WHERE "
            + DbConstants.COLUMN_PACKID + " = " + packId;


    Cursor c = database.rawQuery(selectQuery, null);

    if (c != null)
        c.moveToFirst();

    MenuDetailBean menuDetailBean = new MenuDetailBean();
    menuDetailBean.setTIME(((c.getString(c.getColumnIndex(DbConstants.COLUMN_TIME)))));
    menuDetailBean.setDATE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_DATE)))));
    menuDetailBean.setSUBPACKAGE_NAME(((c.getString(c.getColumnIndex(DbConstants.COLUMN_SUBPACKAGENAME)))));
    menuDetailBean.setPRICE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_PRICE)))));
    menuDetailBean.setTOTAL_PRICE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_TOTAL_PRICE)))));
    menuDetailBean.setMEMBER(((c.getString(c.getColumnIndex(DbConstants.COLUMN_MEMBER)))));
    menuDetailBean.setORDER_TYPE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_ORDER_TYPE)))));
    menuDetailBean.setMENUITEMS(((c.getString(c.getColumnIndex(DbConstants.COLUMN_MENUITEMS)))));
    menuDetailBean.setCURRENT_DATE(((c.getString(c.getColumnIndex(DbConstants.COLUMN_CURRENTDATE)))));
    return menuDetailBean;
}


public static int deteteTableData(Context context, String tableName) {
    int status = 0;
    status = DbAccesser.getInstance(context).deleteTable(tableName);

    return status;
}


public static void deleteOrderAfterTEnDays(Context context) {
    Cursor cursor = DbAccesser.getInstance(context).raw_query("delete from new_order where current_datetime < default current_timestamp - INTERVAL 10 DAY", null);
    Log.e("CURSOR", "" + cursor);
}


// get bill by particular date and outletId
public static CartItemBean getOrderBillByOutlet(Context context, CartItemBean bean) {
    CartItemBean cartItemBean = new CartItemBean();

    String[] params = new String[]{bean.getCOLUMN_PACKID(), bean.getCOLUMN_MEMBER(), bean.getCOLUMN_DATE(), bean.getCOLUMN_TIME()};

    Cursor cursor = DbAccesser.getInstance(context).raw_query("select column_id,name,SUM(order_billing) from cart where order_date=? AND outlets_id=?", params);


    if (cursor != null) {
        if (cursor.moveToFirst()) {
        }

    }
    return cartItemBean;

}

public static void updateRetailerList(Context context, CartItemBean cartItemBean) {


    ContentValues values = new ContentValues();
    DbHelper dbHelper = new DbHelper(context);
    SQLiteDatabase database;
    database = dbHelper.getWritableDatabase();

    values.put(DbConstants.COLUMN_MEMBER, cartItemBean.getCOLUMN_MEMBER());
    values.put(DbConstants.COLUMN_DATE, cartItemBean.getCOLUMN_DATE());
    values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TIME());
    values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_ORDER_TYPE());
    values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TOTAL_PRICE());
    values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_ORDER_TYPE());
    values.put(DbConstants.COLUMN_TIME, cartItemBean.getCOLUMN_TOTAL_PRICE());
    values.put(DbConstants.COLUMN_SUBPACKAGEID, cartItemBean.getCOLUMN_SUBPACKAGE_ID());
    values.put(DbConstants.COLUMN_SUBPACKAGENAME, cartItemBean.getCOLUMN_SUBPACKAGE_NAME());
    values.put(DbConstants.COLUMN_CURRENTDATE, cartItemBean.getCOLUMN_CURRENT_DATE());


    String sql2 = "UPDATE " + DbConstants.TABLE_CART + " SET " +
            DbConstants.COLUMN_MEMBER + " = '" + cartItemBean.getCOLUMN_MEMBER() + "', "
            + DbConstants.COLUMN_DATE + " = '" + cartItemBean.getCOLUMN_DATE() + "', "
            + DbConstants.COLUMN_TIME + " = '" + cartItemBean.getCOLUMN_TIME() + "', "
            + DbConstants.COLUMN_SUBPACKAGEID + " = '" + cartItemBean.getCOLUMN_SUBPACKAGE_ID() + "', "
            + DbConstants.COLUMN_SUBPACKAGENAME + " = '" + cartItemBean.getCOLUMN_SUBPACKAGE_NAME() + "', "
            + DbConstants.COLUMN_CURRENTDATE + " = '" + cartItemBean.getCOLUMN_CURRENT_DATE() + "', "
            + DbConstants.COLUMN_TOTAL_PRICE + " = '" + cartItemBean.getCOLUMN_TOTAL_PRICE() + "' "

            + " WHERE " +
            DbConstants.COLUMN_PACKID + " = '" + cartItemBean.getCOLUMN_PACKID() + "' AND "
            + DbConstants.COLUMN_USERID + " = '" + cartItemBean.getCOLUMN_USERID() + "'";

    database.execSQL(sql2);
    Log.e("UPDATE", sql2);

}

public static void deleteCartItem(Context context, String packId, String userId) {
    DbHelper dbHelper = new DbHelper(context);
    SQLiteDatabase database;
    database = dbHelper.getWritableDatabase();
    database.delete(DbConstants.TABLE_CART, DbConstants.COLUMN_PACKID + "=? AND "+ DbConstants.COLUMN_USERID + "=?", new String[]{packId, userId});
    database.close();

}`

通過創建一個表,每個表項都反映一個關聯,可以將多個項目關聯到每個類別。

例如,假設您有一個玩具數據庫,如該答案結尾處所引用(請參閱“ MCVE基礎”)。

創建表並添加一些關聯:

create table associations (id int, iid int);
insert into associations values (1, 1);
insert into associations values (1, 2);
insert into associations values (1, 3);
insert into associations values (2, 4);
insert into associations values (2, 5);
insert into associations values (3, 6);
insert into associations values (3, 7);

然后,您可以檢索所有類別的項目:

select cat, name from cats inner join associations using(id) inner join items using (iid);

輸出:

cat          name
-----------  ----------
soup         tomato
soup         sour
soup         corn
namkeen      katchori
namkeen      aloo
stall        tikija
stall        patties

或更緊湊的輸出:

select cat, group_concat(name, ', ') 
from cats inner join
     associations using(id) inner join 
     items using (iid)
group by cat
order by id;

輸出:

cat          group_concat(name, ', ')
-----------  ------------------------
soup         tomato, sour, corn
namkeen      katchori, aloo
stall        tikija, patties

我不確定您所說的“回收視圖”是什么意思,也許是因為我在純SQLite中工作(沒有其他語言,就像您顯然使用的那樣)。
我希望這兩種表示形式中的一種適合您-或幫助您實現目標。

MCVE基金會
(我在測試環境中做了一個.dump ,我將其粗略地拼湊起來以證明這個想法。請考慮對下一個涉及SQLite的問題進行類似的處理。這對於應答器來說更容易,從而對您來說也更快。為您提供更緊密的解決方案,並經常防止誤會。
閱讀為什么我應該為我認為是非常簡單的SQL查詢提供MCVE? 如果你喜歡。):

PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE table_1 (a int, b int, c int);
INSERT INTO table_1(a,b,c) VALUES(1,5,7);
INSERT INTO table_1(a,b,c) VALUES(2,10,14);
CREATE TABLE table_2 (a int, c int);
INSERT INTO table_2(a,c) VALUES(3,11);
INSERT INTO table_2(a,c) VALUES(6,22);
CREATE TABLE cats (id int, cat varchar(20));
INSERT INTO cats(id,cat) VALUES(1,'soup');
INSERT INTO cats(id,cat) VALUES(2,'namkeen');
INSERT INTO cats(id,cat) VALUES(3,'stall');
CREATE TABLE items (iid int, name varchar(20));
INSERT INTO items(iid,name) VALUES(1,'tomato');
INSERT INTO items(iid,name) VALUES(2,'sour');
INSERT INTO items(iid,name) VALUES(3,'corn');
INSERT INTO items(iid,name) VALUES(4,'katchori');
INSERT INTO items(iid,name) VALUES(5,'aloo');
INSERT INTO items(iid,name) VALUES(6,'tikija');
INSERT INTO items(iid,name) VALUES(7,'patties');
COMMIT;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM