如何将Json数据存储到Sqlite中?

时间:2016-07-28 12:27:12

标签: android json sqlite

您好我正在创建一个应用程序,我希望将数据从移动设备发送到服务器。但问题是数据仅在服务器在线/ Up时反映在网站上。当服务器处于离线状态时,我得到响应400或502等数据只显示在移动屏幕上它没有反映在server.so我想创建Sqlite数据库,所以当我读取数据存储在数据库中,并希望上传数据,这是服务器成为online.this jon我想插入sqlite.i我是android的新手,所以我不知道如何将这个json插入sqlite.please任何人帮助我。谢谢先进

    Button StartButton = (Button) findViewById(R.id.startButton);        
    StartButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            view.setVisibility(View.GONE);
        }
    });

6 个答案:

答案 0 :(得分:1)

我的朋友只是做了以下事情:

  1. 定义此类,它将执行与数据库创建和操作相关的所有操作,并根据您的需要在此类中进行更改。

    DatabaseHandler.java
    
    
    
     public class DatabaseHandler extends SQLiteOpenHelper {
            private static final int DATABASE_VERSION = 1;
            private static final String DATABASE_NAME = "Demo";
            private static final String TABLE_Demo = "demo";
            private static final String KEY_ID = "id";
            private static final String KEY_PATIENT_ID= "patientId";
            private static final String KEY_ReadingType= "readingType";
            private static final String KEY_DeviceMACId= "deviceMACId"; 
            private static final String KEY_DeviceData = "deviceData ";
    
      private static final String KEY_DeviceType= "deviceType";  
            String CREATE_DEMO_TABLE = "CREATE TABLE " + TABLE_Demo +   "("+   
            KEY_ID + " INTEGER PRIMARY KEY,"+ KEY_ReadingType+ " INTEGER ,"  
            +  KEY_DeviceMACId +  "TEXT,"+ KEY_DeviceData + " TEXT,"     
            + KEY_DeviceType +  " TEXT" + ")"; 
    
                public DatabaseHandler(Context context) {
                    super(context, DATABASE_NAME, null, 
    
                }
    
                public void onCreate(SQLiteDatabase db) {
                    db.execSQL(CREATE_DEMO_TABLE);
                }
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                    db.execSQL("DROP TABLE IF EXISTS " + TABLE_Demo );
                    onCreate(db);
                }
    
                void addJson(JsonObject json) {
                    SQLiteDatabase db = this.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put(KEY_PATIENT_ID,   json.getString("patientId")); 
                values.put(KEY_ReadingType,json.getString("readingType"));       
                    values.put(KEY_DeviceMACId, json.getString("deviceMACId")); 
                    values.put(KEY_DeviceData , json.getString("deviceData")); 
                    values.put(KEY_DeviceType, json.getString("deviceType")); 
                    db.insert(TABLE_Demo , null, values);
                    db.close();
                }
    
            }
    
  2. 现在创建这个类的对象并将你的json对象存储到数据库中,如下所示:

    DatabaseHandler db = new DatabaseHandler (context); 
         // context of your activity or fragment
        try
        {
        db.addJson(JsonObject json);
    

    //这里json是你需要保存在数据库中的json对象。         } catch(例外e)           {           }

答案 1 :(得分:0)

您可以为此json创建模型对象。然后,您可以将模型对象保存到数据库。尝试查找有关SQLite数据库的一些示例,并在项目中使用它。

答案 2 :(得分:0)

首先你尝试将一些json数据发布到server.So你从服务器得到的响应是up / not.So检查你的响应代码。如果响应代码不等于200,你将生成的json插入Sqlite数据库。经常检查与服务器的连接是否正常。如果服务器在线,则意味着从SqliteDB获取json数据并将其发布到服务器

Sqlite数据库的示例 http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 连接服务器的示例 http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ 使用volley库进行服务器连接可以获得

的错误响应

答案 3 :(得分:0)

  1. 使用sq-lite数据库中的所有字段创建一个数据库。
  2. 在数据表中放置一个名为isUpdated extra的字段。
  3. 运行一个单独的线程来检查网络并将数据更新到远程数据库。
  4. 线程函数[检查互联网可用性,如果互联网可用更新数据到远程数据库,则在更新成功时将sq-lite数据库中的isUpdated状态更新为true

    < / LI>
  5. 主线程将定期更新本地sq-lite数据库,即使在没有互联网的情况下isUpdated状态为false

  6. 这可能对您有所帮助

    使用this

    检查网络可用性

    更新远程数据库需要Web服务

     void PutRequest(String URL)
     {
        Ion.with(mContext)
                .load("PUT",URL)
                .setBodyParameter("name","foo")
                .asString();
    
     }
    

    了解有关Ion

    的更多信息

答案 4 :(得分:0)

public class DataBase {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "demo";
    private static final String TABLE_NAME = "device_data";
    private static final String KEY_ID = "id";
    private static final String KEY_PATIENT_ID = "patientId";
    private static final String KEY_ReadingType = "readingType";
    private static final String KEY_DeviceMACId = "deviceMACId";
    private static final String KEY_DeviceData = "deviceData ";
    private static final String KEY_DeviceType = "deviceType";
    private static final String KEY_TimeStamp = "timeStamp";
    private static final String KEY_AssetId = "assetId";
    private static final String KEY_GeoLocationLattitude = "geoLocationLatitude";
    private static final String KEY_GeoLocationLongitude = "geoLocationLongitude";
    private static final String KEY_ClientId = "clientId";
    private static final String KEY_DeviceRawData = "deviceRawData";

    private final Context context;
    private DataBaseHelper dbHelper;
    public SQLiteDatabase db;

    static final String DATABASE_CREATE = "create table " + TABLE_NAME + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ReadingType + " INTEGER ,"
            + KEY_DeviceMACId + "TEXT," + KEY_DeviceData + " TEXT,"
            + KEY_DeviceType + " TEXT," + KEY_TimeStamp + "TEXT," + KEY_AssetId
            + "INTEGER," + KEY_GeoLocationLattitude + "TEXT,"
            + KEY_GeoLocationLongitude + "TEXT," + KEY_ClientId + "INTEGER,"
            + KEY_DeviceRawData + "TEXT" + ")";

    public DataBase(Context _context) {
        context = _context;
        dbHelper = new DataBaseHelper(context, DATABASE_NAME, null,
                DATABASE_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    void addJson(JSONObject json) throws JSONException {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        try {
            values.put(KEY_PATIENT_ID, json.getString("patientId"));
            values.put(KEY_ReadingType, json.getString("readingType"));
            values.put(KEY_DeviceMACId, json.getString("deviceMACId"));
            values.put(KEY_DeviceData, json.getString("deviceData"));
            values.put(KEY_DeviceType, json.getString("deviceType"));
            values.put(KEY_TimeStamp, json.getString("deviceType"));
            values.put(KEY_AssetId, json.getString("deviceType"));
            values.put(KEY_GeoLocationLattitude, json.getString("deviceType"));
            values.put(KEY_GeoLocationLongitude, json.getString("deviceType"));
            values.put(KEY_ClientId, json.getString("deviceType"));
            values.put(KEY_DeviceRawData, json.getString("deviceType"));

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            System.out.println("JsonException........");
            e.printStackTrace();
        }

        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public DataBase open() throws SQLException {
        db = dbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        db.close();
    }

    public SQLiteDatabase getDatabaseInstance() {
        return db;
    }

答案 5 :(得分:0)

@Dhiraj -i got exception..
08-01 12:05:45.447: I/System.out(4109): In try....com.example.healthdeviceprofilee.DataBase@42187568
08-01 12:05:45.447: I/System.out(4109): JsonException........
08-01 12:05:45.447: W/System.err(4109): org.json.JSONException: No value for patientId
08-01 12:05:45.447: W/System.err(4109):     at org.json.JSONObject.get(JSONObject.java:355)
08-01 12:05:45.447: W/System.err(4109):     at org.json.JSONObject.getString(JSONObject.java:515)
08-01 12:05:45.447: W/System.err(4109):     at com.example.healthdeviceprofilee.DataBase.addJson(DataBase.java:59)
08-01 12:05:45.447: W/System.err(4109):     at com.example.healthdeviceprofilee.DashboardActivity$RestConnection.onPostExecute(DashboardActivity.java:895)
08-01 12:05:45.447: W/System.err(4109):     at com.example.healthdeviceprofilee.DashboardActivity$RestConnection.onPostExecute(DashboardActivity.java:1)
08-01 12:05:45.447: W/System.err(4109):     at android.os.AsyncTask.finish(AsyncTask.java:632)
08-01 12:05:45.447: W/System.err(4109):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-01 12:05:45.447: W/System.err(4109):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
08-01 12:05:45.447: W/System.err(4109):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-01 12:05:45.447: W/System.err(4109):     at android.os.Looper.loop(Looper.java:136)
08-01 12:05:45.447: W/System.err(4109):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-01 12:05:45.458: W/System.err(4109):     at java.lang.reflect.Method.invokeNative(Native Method)
08-01 12:05:45.458: W/System.err(4109):     at java.lang.reflect.Method.invoke(Method.java:515)
08-01 12:05:45.458: W/System.err(4109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-01 12:05:45.458: W/System.err(4109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-01 12:05:45.458: W/System.err(4109):     at dalvik.system.NativeStart.main(Native Method)
08-01 12:05:45.458: E/SQLiteLog(4109): (1) near "null": syntax error
08-01 12:05:45.458: E/SQLiteDatabase(4109): Error inserting 
08-01 12:05:45.458: E/SQLiteDatabase(4109): android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO device_data(null) VALUES (NULL)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at com.example.healthdeviceprofilee.DataBase.addJson(DataBase.java:77)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at com.example.healthdeviceprofilee.DashboardActivity$RestConnection.onPostExecute(DashboardActivity.java:895)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at com.example.healthdeviceprofilee.DashboardActivity$RestConnection.onPostExecute(DashboardActivity.java:1)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.os.AsyncTask.finish(AsyncTask.java:632)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.os.Looper.loop(Looper.java:136)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at java.lang.reflect.Method.invokeNative(Native Method)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at java.lang.reflect.Method.invoke(Method.java:515)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-01 12:05:45.458: E/SQLiteDatabase(4109):     at dalvik.system.NativeStart.main(Native Method)