gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:47:50 28 4
gpt4 key购买 nike

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

为了将数据存储到 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 类的对象并调用 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();

关于android - 如何将解析后的 JSON 数据存储到 SQLite 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25974268/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com