如何将解析的JSON数据存储到SQLite中

时间:2014-09-22 12:34:09

标签: android json sqlite

我已编写代码将JSON数据解析为ListView,但现在在将数据显示到ListView之前,我想将其存储到SQLite数据库中,然后想要在List中显示。

为了将数据存储到SQLite中,我也编写了数据库助手类,但现在我有点混淆了如何使用这个类将解析后的数据直接存储到sqlite中

public class MainActivity extends Activity {

ArrayList<Actors> actorsList;   
ActorAdapter adapter;

SQLiteDB sqliteDB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sqliteDB = new SQLiteDB (this);

    actorsList = new ArrayList<Actors>();

    new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");

    ListView listview = (ListView)findViewById(R.id.list);
    adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);      
    listview.setAdapter(adapter);       
    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();              
        }
    });
}


class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading, please wait");
        dialog.setTitle("Connecting server");
        dialog.show();
        dialog.setCancelable(false);
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            //------------------>>
            HttpGet httppost = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);

                JSONObject jsono = new JSONObject(data);
                JSONArray jarray = jsono.getJSONArray("actors");

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject object = jarray.getJSONObject(i);

                    Actors actor = new Actors();                        
                    actor.setName(object.getString("name"));

                    actorsList.add(actor);
                }
                return true;
            }

            //------------------>>

        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected void onPostExecute(Boolean result) {
        dialog.cancel();
        adapter.notifyDataSetChanged();
        if(result == false)
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
    }
  }
}

SQLite的

public class SQLiteDB {

    public static final String KEY_ID = "id";
    public static final String KEY_NAME = "name";

    private static final String TAG = "DBAdapter";
    private static final String DATABASE_NAME = "SQLiteDB";

    private static final String TABLE_NAME = "sample";
    private static final int DATABASE_VERSION = 1;

    private static final String CREATE_TABLE = 
            "create table sample (id text primary key autoincrement, name text not null);";

    private final Context context;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public SQLiteDB(Context ctx) {

        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {           
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {           
        try {
                db.execSQL(CREATE_TABLE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {      
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS sample");
        onCreate(db);
        }
    }

    //---open SQLite DB---
    public SQLiteDB open() throws SQLException {    
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---close SQLite DB---
    public void close() {   
        DBHelper.close();
    }

    //---insert data into SQLite DB---
    public long insert(String name) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);      
        return db.insert(TABLE_NAME, null, initialValues);
    }

    //---Delete All Data from table in SQLite DB---
    public void deleteAll() {
        db.delete(TABLE_NAME, null, null);
    }

    //---Get All Contacts from table in SQLite DB---
    public Cursor getAllData() {
        return db.query(TABLE_NAME, new String[] {KEY_NAME}, 
                null, null, null, null, null);
    }

}

1 个答案:

答案 0 :(得分:5)

创建SQLiteDB类的对象并调用insert(...)方法将数据存储在DB中,如:

            SQLiteDB dba=new SQLiteDB(MainActivity.this);//Create this object in onCreate() method

            dba.open();

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);

                Actors actor = new Actors();                        
                actor.setName(object.getString("name"));
                dba.insert(object.getString("name"));// Insert record in your DB
                actorsList.add(actor);
            }

             dba.close();