我试图创建一个从sql server获取数据并在listview中显示的应用程序,但我也想在sqlite数据库中保存json。为此我创建了以下SqliteDB类,但我对如何将json数据发送到此类感到困惑。
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 = "departmentList";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_TABLE =
"create table departmentList (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);
}
}
接收json响应的类
public class DeptActivity extends Activity{
ArrayAdapter<String> adapter;
ListView listv;
Context context;
ArrayList<String> data;
SqliteDB sqlite;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dept);
sqlite = new SqliteDB(DeptActivity.this);
setupActionBar();
data = new ArrayList<String>();
listv = (ListView) findViewById(R.id.lv_dept);
context = this;
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, data);
listv.setAdapter(adapter);
Toast.makeText(this,"Loading Please Wait..",Toast.LENGTH_SHORT).show();
new AsyncLoadDeptDetails().execute();
}
公共类AsyncLoadDeptDetails扩展 的AsyncTask&GT; { ArrayList deptTable = null;
@Override
public ArrayList<DeptTable> doInBackground(Void... params) {
// TODO Auto-generated method stub
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetDepartmentDetails();
JSONParser parser = new JSONParser();
Log.i( "department list", jsonObj.toString());
deptTable = parser.parseDepartment(jsonObj);
sqlite();
} catch (Exception e) {
}
return deptTable;
}
//method to insert data json in sqlite
private void sqlite() {
// TODO Auto-generated method stub
sqlite.open();
for(int i=0; i<deptTable.size(); i++) {
sqlite.insert(deptTable.get(i).toString());
}
sqlite.close();
}
@Override
protected void onPostExecute(ArrayList<DeptTable> result) {
// TODO Auto-generated method stub
for (int i = 0; i < result.size(); i++) {
data.add(result.get(i).getNo() + " " + result.get(i).getName());
}
adapter.notifyDataSetChanged();
Toast.makeText(context,"Loading Completed",Toast.LENGTH_SHORT).show();
}
Logcat错误
Error inserting name=com.example.db_client.DeptTable@b3e53870
android.database.sqlite.SQLiteException: no such table: departmentList (code 1): , while compiling: INSERT INTO departmentList(name) VALUES (?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
at com.example.db_client.SqliteDB.insert(SqliteDB.java:73)
at com.example.db_client.DeptActivity$AsyncLoadDeptDetails.sqlite(DeptActivity.java:91)
at com.example.db_client.DeptActivity$AsyncLoadDeptDetails.doInBackground(DeptActivity.java:68)
at com.example.db_client.DeptActivity$AsyncLoadDeptDetails.doInBackground(DeptActivity.java:1)
答案 0 :(得分:0)
我怀疑没有调用SQLiteOpenHelper的onCreate方法。这就是为什么没有创建数据库表的原因。请在您的DatabaseHelper的onCreate中登录并检查它是否正在打印。还可以尝试将SQLiteOpenHelper用作非静态内部类,即删除SQLiteDB类并直接使用DatabaseHelperClass构造函数。
答案 1 :(得分:0)
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
问题是你的CREATE_TABLE
语句有错误,但你的onCreate
函数抑制了这个错误,因此SQLiteOpenHelper
认为它成功,并且数据库可用。
删除try
/ catch
,然后移除您应用的数据(强制onCreate
再次执行)。
然后修复错误消息中的错误。