微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);
    }

}

解决方法:

创建sqliteDB类的Object并调用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();  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐