我已经使用 JSONObject 从外部数据库成功访问了数据,但我的问题是我要将它保存到 sqlite 数据库。到我检索数据时,我只从 sqlite 获得了最后一行。主要问题是从sqlite而不是JSON获取数据,也许我在分配或检索时出错了......这里的noobness状态......谢谢
添加 SQLITE 代码之前的代码:
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
添加到 SQlite:
{ // products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
//individually get each arrays
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
//code to add each retrieved data from JSONArray to Sqlite
db.addContact(new Menu(id.toString(), name.toString()));
}
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Menu> contacts = db.getAllContacts();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
for (Menu cn : contacts) {
// Writing Contacts to log
// adding each child node to HashMap key => value
map.put(TAG_PID, cn.getID().toString());
map.put(TAG_NAME,cn.getName().toString());
// adding HashList to ArrayList
productsList.add(map);
}
程序的另一部分:
ListAdapter adapter = new SimpleAdapter(
Main_Activity.this, productsList,
R.layout.activity_view_products, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
另一个代码:
// Adding new contact
void addContact(Menu contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, contact.getID()); // Contact Name
values.put(KEY_NAME, contact.getName()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting All Contacts
public List<Menu> getAllContacts() {
List<Menu> contactList = new ArrayList<Menu>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Menu contact = new Menu();
contact.setID((cursor.getString(0).toString()));
contact.setName(cursor.getString(1).toString());
Log.d("Menu: ", contact.getID().toString());
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}