Android json解析并存储到数据库中

时间:2015-04-23 10:00:33

标签: android json sqlite

我正在创建一个拥有数据库的应用程序,现在我正在尝试使用此方法存储数据并获取错误javanullpointer,

JSONParser jParser = new JSONParser();
                    JSONObject json = jParser.getJSONFromUrl(url);
                        // TODO Auto-generated method stub


                        JSONArray Erate= json.getJSONArray("Erates");
                        if(Erate!=null)
                        {

                        // looping through All Contacts
                        for(int i = 0; i < Erate.length(); i++){
                            JSONObject c = Erate.getJSONObject(i);
                            Cursor cr = db.rawQuery("select * from `rates` where `id`='"+c.getString("id")+"'",null);

                                String query=
                            "Insert into rates(id,kondisi,condition,tenor,erate,erateDB)"+
                            "values("+
                            c.getString("id")+",'"+

                            c.getString("....")
                            +"')";
                                db.execSQL(query);
                            Log.d("Insert",query);

                            cr.close();}
                        }

然后我尝试另一种方法(这也给出了相同的错误)

          for (int i = 0; i < Erates.length(); i++) {
                    JSONObject c = Erates.getJSONObject(i);
                int id = c.getInt(TAG_ER_ID);
                    int tenor = c.getInt(TAG_ER_TENOR);
                    String ko = c.getString(TAG_ER_K);
                    String co = c.getString(TAG_ER_C);
                    double rate = c.getDouble(TAG_ER_RATE);
                    double ratedb = c.getDouble(TAG_ER_RATE_DB);

                    Log.d("Response test: ", id + "\n" + tenor + "\n" + ko
                            + "\n" + co + "\n" + rate + "\n" + ratedb);
                    /**
                     * Updating parsed JSON data into db
                     * */
                    db.saveEntryEffectiveRate(id, tenor,ko,co,
                     rate,ratedb);
                }

数据库中的saveEntryEffectiveRate:

public void saveEntryEffectiveRate(int id, int tenor,String ko,String co, double rate,
            double ratedb) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues valuesER = new ContentValues();
        valuesER.put(KEY_ER_ID, id);
        valuesER.put(KEY_ER_TENOR, tenor);
        valuesER.put(KEY_ER_KO, ko);
        valuesER.put(KEY_ER_CO, co);
        valuesER.put(KEY_ER_RATE, rate);
        valuesER.put(KEY_ER_RATE_DB, ratedb);
        db.insert(TABLE_EFFECTIVE_RATE, null, valuesER);
    }

更新:logcat:

04-23 16:44:14.044: E/AndroidRuntime(6752): FATAL EXCEPTION: main
04-23 16:44:14.044: E/AndroidRuntime(6752): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{www.mandiritunasfinancemobile.co.id.a1s2d3f4g5h6j7k8l9.p0.comcom/www.mandiritunasfinancemobile.co.id.a1s2d3f4g5h6j7k8l9.p0.comcom.MainActivity}: java.lang.NullPointerException
04-23 16:44:14.044: E/AndroidRuntime(6752):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1544)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at android.os.Looper.loop(Looper.java:123)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at android.app.ActivityThread.main(ActivityThread.java:3647)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at java.lang.reflect.Method.invokeNative(Native Method)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at java.lang.reflect.Method.invoke(Method.java:507)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at dalvik.system.NativeStart.main(Native Method)
04-23 16:44:14.044: E/AndroidRuntime(6752): Caused by: java.lang.NullPointerException
04-23 16:44:14.044: E/AndroidRuntime(6752):     at www.mandiritunasfinancemobile.co.id.a1s2d3f4g5h6j7k8l9.p0.comcom.MainActivity.<init>(MainActivity.java:55)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at java.lang.Class.newInstanceImpl(Native Method)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at java.lang.Class.newInstance(Class.java:1409)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
04-23 16:44:14.044: E/AndroidRuntime(6752):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1536)
04-23 16:44:14.044: E/AndroidRuntime(6752):     ... 11 more

更新:DB:

public class DatabaseMaster2 extends SQLiteOpenHelper {
    SQLiteDatabase mydb;
    // Database Version
    private static final int DATABASE_VERSION = 7;

    // Database Name
    private static final String DATABASE_NAME = "Rates";

    // Table Names
    //effective_rate
    public static final String KEY_ER_ID = "er_id";
    public static final String KEY_ER_TENOR = "ER_tenor";
    public static final String KEY_ER_KO = "ER_ko";
    public static final String KEY_ER_CO = "ER_co";
    public static final String KEY_ER_RATE = "ER_rate";
    public static final String KEY_ER_RATE_DB = "ER_rate_DB" ;
    //ER_Linker
    public static final String KEY_ER_L_ID = "kondisi_id";
    public static final String KEY_ER_L_K = "kondisi";
    public static final String KEY_ER_L_C = "condition";
    //AS_Linker
    public static final String KEY_AS_L_ID = "asuransi_type_id";
    public static final String KEY_AS_L_Ty = "asuransi_type";
    //AS_linker_zona
    public static final String KEY_AS_L_Z_ID = "aslz_id";
    public static final String KEY_AS_L_Z_ZONA = "aslz_zona";
    public static final String KEY_AS_L_Z_ZONE = "aslz_zone";
    // Asuransi rate
    public static final String KEY_AS_ID = "as_id";
    public static final String KEY_AS_ZO = "AS_zona";
    public static final String KEY_AS_TENOR = "AS_tenor";
    public static final String KEY_AS_TLO = "TLO";
    public static final String KEY_AS_COMPREHENSIVE = "Comprehensive";
    public static final String KEY_AS_COMBINE = "Combine";
    //the tables
    public static final String TABLE_EFFECTIVE_RATE = "effective_rate";
    public static final String TABLE_ASURANSI_RATE = "asuransi_rate";
    public static final String TABLE_AS_LINKER = "as_linker";
    public static final String TABLE_AS_L_ZONA= "as_l_zona";
    public static final String TABLE_ER_LINKER = "er_linker";

    public DatabaseMaster2(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        try {
            db.beginTransaction();
            db.execSQL("CREATE TABLE " + TABLE_ER_LINKER + " ("+ KEY_ER_L_K + " TEXT NOT NULL," + KEY_ER_L_C+ " TEXT NOT NULL)");
            db.execSQL("CREATE TABLE " + TABLE_AS_LINKER + " ("+ KEY_AS_L_Ty + " TEXT NOT NULL)");
            db.execSQL("CREATE TABLE " + TABLE_AS_L_ZONA + " ("+ KEY_AS_L_Z_ZONA + " TEXT NOT NULL, " + KEY_AS_L_Z_ZONE + " TEXT NOT NULL)");
            db.execSQL("CREATE TABLE " + TABLE_EFFECTIVE_RATE + " ("+ KEY_ER_ID + " INTEGER PRIMARY KEY, " + KEY_ER_TENOR+" INTEGER," +KEY_ER_KO+" TEXT NOT NULL, "+KEY_ER_CO+" TEXT NOT NULL, "+KEY_ER_RATE+" REAL, "+ KEY_ER_RATE_DB + " REAL)");
            db.execSQL("CREATE TABLE " + TABLE_ASURANSI_RATE + " ("+ KEY_AS_ID + " INTEGER PRIMARY KEY, "+ KEY_AS_ZO + " INTEGER, " + KEY_AS_TENOR+ " INTEGER," + KEY_AS_TLO + " REAL,"+ KEY_AS_COMPREHENSIVE + " REAL," + KEY_AS_COMBINE+ " REAL)");
            // Inserts pre-defined departments


            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_EFFECTIVE_RATE);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ASURANSI_RATE);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ER_LINKER);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_AS_LINKER);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_AS_L_ZONA);
        onCreate(db);

    }

    public int updateEntryEffectiveRate(EntryEffectiveRate er) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ER_ID, er.getERId());
        values.put(KEY_ER_TENOR, er.getERTenor());
        values.put(KEY_ER_RATE, er.getERrate());
        values.put(KEY_ER_RATE_DB, er.getERrateDB());

        // updating row
        return db.update(TABLE_EFFECTIVE_RATE, values, KEY_ER_ID + " = ?",
                new String[] { String.valueOf(er.getERId()) });
    }

    //
    public void deleteEntryEffectiveRate(long er_id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_EFFECTIVE_RATE, KEY_ER_ID + " = ?",
                new String[] { String.valueOf(er_id) });
    }



    public void saveEntryEffectiveRate(int id, int tenor,String ko,String co, double rate,
            double ratedb) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues valuesER = new ContentValues();
        valuesER.put(KEY_ER_ID, id);
        valuesER.put(KEY_ER_TENOR, tenor);
        valuesER.put(KEY_ER_KO, ko);
        valuesER.put(KEY_ER_CO, co);
        valuesER.put(KEY_ER_RATE, rate);
        valuesER.put(KEY_ER_RATE_DB, ratedb);
        db.insert(TABLE_EFFECTIVE_RATE, null, valuesER);
    }

    public void saveEntryAsuransiRate(int ASid,int ASzo,int AStenor,double tlo,double comp,double comb) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues valuesAS = new ContentValues();
        valuesAS.put(KEY_AS_ID, ASid);
        valuesAS.put(KEY_AS_ZO, ASzo);
        valuesAS.put(KEY_AS_TENOR, AStenor);
        valuesAS.put(KEY_AS_TLO, tlo);
        valuesAS.put(KEY_AS_COMPREHENSIVE, comp);
        valuesAS.put(KEY_AS_COMBINE, comb);
        db.insert(TABLE_ASURANSI_RATE, null, valuesAS);
    }

    public void saveKondisi(String K,String C) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues valuesK = new ContentValues();
        valuesK.put(KEY_ER_L_K,K );
        valuesK.put(KEY_ER_L_C, C);
        db.insert(TABLE_ER_LINKER, null, valuesK);
    }

    public void saveTipeAsuransi(String ty) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues valuesTA = new ContentValues();
        valuesTA.put(KEY_AS_L_Ty, ty);
        db.insert(TABLE_AS_LINKER, null, valuesTA);
    }

    public void saveZona(String za,String ze) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues valuesZO = new ContentValues();
        valuesZO.put(KEY_AS_L_Z_ZONA, za);
        valuesZO.put(KEY_AS_L_Z_ZONE, ze);
        db.insert(TABLE_AS_L_ZONA, null, valuesZO);
    }


    //
    public void deleteEntryAsuransiRate(long as_id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_ASURANSI_RATE, KEY_AS_ID + " = ?",
                new String[] { String.valueOf(as_id) });
    }

我在mainclass中声明数据库,它将使用DatabaseMaster2 db;数据库master进行解析和存储是扩展sqliteopenhelper的数据库类的名称

我将日志放入以确保解析成功完成。它是。 有关将数据存储到数据库的任何建议吗?

2 个答案:

答案 0 :(得分:3)

首先用getwritable()打开你的数据库....然后试试这段代码

JSONObject json_give_field_1 = jsonArray_items.getJSONObject(0);
    for (int i = 0; i < jsonArray_items.length(); i++) {
        JSONObject fields_value;

        try {           
            cv.put("databasefield", fields_value.getString(field)); 


            db.insert(database_table, null, cv);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

之后,必须通过db.close()关闭数据库; 希望它对你有用

答案 1 :(得分:1)

不使用Json Parser,而是尝试将Gson库从Json转换为String,反之亦然。有关详细示例,请参阅此answer

创建一个包含所需信息的类,然后使用Gson将其序列化。