【问题标题】:How to insert an array to SQLite?如何将数组插入 SQLite?
【发布时间】:2019-10-12 15:42:29
【问题描述】:

我需要将 JSON 加载的数组插入 SQLite 数据库。任何帮助表示赞赏。

JSONObject jsonObj = new JSONObject(jsonStr);


                    JSONArray sites = jsonObj.getJSONArray("Sites");

                    for (int i = 0; i < sites.length(); i++) {
                        JSONObject c = sites.getJSONObject(i);

                        String id = c.getString("id");
                        String nam = c.getString("names");
                        String loc = c.getString("location");

                        HashMap<String, String> sit = new HashMap<>();

                        sit.put("id", id);
                        sit.put("names", name);
                        sit.put("location", loc);

                        array_sites.add(sit);

【问题讨论】:

  • 您想将array_sites 添加到您的SQLite Database 中吗?
  • 是的,正确,我想在数据库中插入array_sites (SQLite)。

标签: android json sqlite


【解决方案1】:

试试这个:

public void addData(ArrayList<String> list){

    int size = list.size();

    SQLiteDatabase db = getWritableDatabase();

    try{
       for (int i = 0; i < size ; i++){
           ContentValues cv = new ContentValues();
           cv.put(KEY_NAME, list.get(i));
           Log.d("Data Inserted ",""+ cv);
           db.insertOrThrow(TABLE_NAME, null, cv);
       }  
       db.close();
    }catch (Exception e){
    Log.e("Exception>>>>", e + " ");
}

从您存储数据的位置调用

addData(array_sites);

我建议ArrayList&lt;String&gt;,您可以使用自己的ArrayList&lt;YourDataType&gt;

【讨论】:

  • 如有任何问题,请发表评论!
猜你喜欢
  • 2014-02-23
  • 1970-01-01
  • 2013-02-05
  • 2016-09-01
  • 1970-01-01
  • 2022-07-21
  • 2020-08-21
  • 2018-11-10
  • 2011-07-22
相关资源
最近更新 更多