在Android中使用Hashmap将数据从json对象保存到SQLite

发布于 2024-11-14 19:55:10 字数 3806 浏览 1 评论 0原文

大家好,我是Android新手,我需要解析json对象并将其显示在listView中,同时将这些数据保存在SQLite中,但是每当我运行项目时都会捕获异常......创建数据库时没有任何数据或其中的价值。

这是我正在尝试的代码:

Bundle bundle = getIntent().getExtras();
        String rfiItems = bundle.getString("allData");
        final ArrayList<HashMap<String, String>> mylist4 = new ArrayList<HashMap<String, String>>();

        try{
            JSONObject jObj = new JSONObject(rfiItems);
            JSONArray data4 = jObj.getJSONArray("data");
            //data4 = json4.getJSONArray("data");
                //Toast.makeText(getApplicationContext(), data4.toString(), Toast.LENGTH_LONG).show();

                    for(int i=0;i<data4.length();i++){                      
                        HashMap<String, String> map = new HashMap<String, String>();    
                        JSONObject e = data4.getJSONObject(i);

                        map.put("id", String.valueOf(i));
                        map.put("rfi_data1", "" + e.getString("country"));                          
                        map.put("rfi_data4", "" + e.getString("state"));
                        map.put("rfi_data5", "" + e.getString("city"));
                        map.put("rfi_data6", "" + e.getString("name"));
                        map.put("rfi_data7", "" + e.getString("about"));


                        DatabaseHelper databaseHelper = new DatabaseHelper(this);
                        SQLiteDatabase db = databaseHelper.getWritableDatabase();
                        ContentValues cv = new ContentValues();
                        cv.put(DatabaseHelper.COUNTRY, e.getString("country"));
                        cv.put(DatabaseHelper.CITY, e.getString("state"));
                        cv.put(DatabaseHelper.STATE, e.getString("city"));
                        cv.put(DatabaseHelper.NAME, e.getString("name"));
                        cv.put(DatabaseHelper.ABOUT, e.getString("about"));

                        db.insert("Baranzan", DatabaseHelper.COUNTRY, cv);
                        db.close();
                        mylist4.add(map);
                    }       
                }catch(JSONException e)        {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                }

                ListAdapter adapter4 = new SimpleAdapter(this, mylist4 , R.layout.item_list4,
                                          new String[] { "rfi_data1", "rfi_data4","rfi_data5","rfi_data6","rfi_data7"}, 
                                     new int[] { R.id.rfi_item_type, R.id.rfi_status,R.id.rfi_title,R.id.rfi_change_date,R.id.rfi_responded_date });
                                          setListAdapter(adapter4); 

和数据库类代码:

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "myonlydb.db";
    public static final String ID = "id";
    public static final String COUNTRY = "country";
    public static final String STATE = "state";
    public static final String CITY = "city";
    public static final String NAME = "name";
    public static final String ABOUT = "about";


    public static final String TAG = "Form"; // optional

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE mytable (_id INTEGER PRIMARY KEY AUTOINCREMENT, country TEXT, state TEXT, city TEXT, name TEXT, about TEXT, );");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        android.util.Log.v("mytable", "Upgrating database will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS mytable");
        onCreate(db);

    }

任何帮助将非常感激,非常感谢

Hello Everyone I am newbie in Android, I need to parse json object and display it in listView and at the same time to save those data in SQLite, but whenever I run the project exception is caught ... the database is created without any data or value in it.

here is the code by which I am trying:

Bundle bundle = getIntent().getExtras();
        String rfiItems = bundle.getString("allData");
        final ArrayList<HashMap<String, String>> mylist4 = new ArrayList<HashMap<String, String>>();

        try{
            JSONObject jObj = new JSONObject(rfiItems);
            JSONArray data4 = jObj.getJSONArray("data");
            //data4 = json4.getJSONArray("data");
                //Toast.makeText(getApplicationContext(), data4.toString(), Toast.LENGTH_LONG).show();

                    for(int i=0;i<data4.length();i++){                      
                        HashMap<String, String> map = new HashMap<String, String>();    
                        JSONObject e = data4.getJSONObject(i);

                        map.put("id", String.valueOf(i));
                        map.put("rfi_data1", "" + e.getString("country"));                          
                        map.put("rfi_data4", "" + e.getString("state"));
                        map.put("rfi_data5", "" + e.getString("city"));
                        map.put("rfi_data6", "" + e.getString("name"));
                        map.put("rfi_data7", "" + e.getString("about"));


                        DatabaseHelper databaseHelper = new DatabaseHelper(this);
                        SQLiteDatabase db = databaseHelper.getWritableDatabase();
                        ContentValues cv = new ContentValues();
                        cv.put(DatabaseHelper.COUNTRY, e.getString("country"));
                        cv.put(DatabaseHelper.CITY, e.getString("state"));
                        cv.put(DatabaseHelper.STATE, e.getString("city"));
                        cv.put(DatabaseHelper.NAME, e.getString("name"));
                        cv.put(DatabaseHelper.ABOUT, e.getString("about"));

                        db.insert("Baranzan", DatabaseHelper.COUNTRY, cv);
                        db.close();
                        mylist4.add(map);
                    }       
                }catch(JSONException e)        {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                }

                ListAdapter adapter4 = new SimpleAdapter(this, mylist4 , R.layout.item_list4,
                                          new String[] { "rfi_data1", "rfi_data4","rfi_data5","rfi_data6","rfi_data7"}, 
                                     new int[] { R.id.rfi_item_type, R.id.rfi_status,R.id.rfi_title,R.id.rfi_change_date,R.id.rfi_responded_date });
                                          setListAdapter(adapter4); 

and databaseclass code:

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "myonlydb.db";
    public static final String ID = "id";
    public static final String COUNTRY = "country";
    public static final String STATE = "state";
    public static final String CITY = "city";
    public static final String NAME = "name";
    public static final String ABOUT = "about";


    public static final String TAG = "Form"; // optional

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE mytable (_id INTEGER PRIMARY KEY AUTOINCREMENT, country TEXT, state TEXT, city TEXT, name TEXT, about TEXT, );");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        android.util.Log.v("mytable", "Upgrating database will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS mytable");
        onCreate(db);

    }

Any help will really be appreciated , THANKS A LOT

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

っ〆星空下的拥抱 2024-11-21 19:55:10

我不确定你做错了什么,但我可以帮助你进行一些调试。

首先你在哪里声明你的表?这与您尝试插入的数据一致吗?

在创建 ContentValue 并调用 insert 的 for 循环中,尝试查看 insert 返回的整数,这是行号或 ID 不记得了。但如果不插入则为-1。如果你得到这个问题可能是某种类型的问题。尝试将字符串保存为 int 或...?

您可以使用的另一个很棒的工具是 sqlite3 命令来检查数据库结构和表。 sqlite3 未安装在 Android 设备上,因此请使用模拟器,或者阅读以下内容以了解如何使其在设备上运行:
如何安装sqlite3

I'm not sure what you doing wrong, but I can help you with some debugging.

First where do you declare your table? Is this consistent with your data trying to insert?

In your for loop where you create your ContentValue and call insert, try to see what integer insert is returning, this is the row number or ID can't remember. But it's -1 if not inserted. If you get this the problem is probably some sort of type problem. Trying to save a string as a int or...?

Another great tool you could use is the sqlite3 command to inspect the database structure and the tables. The sqlite3 is not installed on an android device, so use the emulator for this, or read this on how to make it running on a device:
How to install sqlite3

汹涌人海 2024-11-21 19:55:10

这行是错误的

db.insert("Baranzan", DatabaseHelper.COUNTRY, cv);

尝试

db.insert(DatabaseHelper.COUNTRY, null, cv);

如果您在这里捕获异常

catch(JSONException e)        {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                }

那么您应该提供来自 logcat 的日志以获取更多信息

this line is wrong

db.insert("Baranzan", DatabaseHelper.COUNTRY, cv);

try

db.insert(DatabaseHelper.COUNTRY, null, cv);

if you caught exception here

catch(JSONException e)        {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                }

then you should provide log from logcat for more information

傾旎 2024-11-21 19:55:10

编辑此行

db.insert("Baranzan", DatabaseHelper.COUNTRY, cv);

db.insert("mytable", null, cv);

edit this line

db.insert("Baranzan", DatabaseHelper.COUNTRY, cv);

to

db.insert ("mytable", null, cv);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文