save data to SQLite from json object using Hashmap

2019-09-17 15:58发布

问题:

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

回答1:

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



回答2:

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



回答3:

edit this line

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

to

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