机器人:如何保存从SQL Server数据,Android的SQLite数据库 [英] android:how to save data from sql server to android's sqlite database
问题描述
我试图创建一个应用程序从SQL Server中获取数据,并在列表视图中显示,但我也想保存在SQLite数据库的JSON。为此,我创建了以下SqliteDB类,但我很困惑如何JSON数据发送到这个类。
公共类SqliteDB {
公共静态最后弦乐KEY_ID =ID;
公共静态最后弦乐KEY_NAME =名;
私有静态最后字符串变量=DBAdapter;
私有静态最后弦乐DATABASE_NAME =SQLiteDB;
私有静态最后弦乐TABLE_NAME =departmentList;
私有静态最终诠释DATABASE_VERSION = 1;
私有静态最后弦乐CREATE_TABLE =
创建表departmentList(ID文本主键自动增量,名称文字NOT NULL);;
私人最终上下文的背景下;
私人DatabaseHelper DBHelper;
私人SQLiteDatabase分贝;
公共SqliteDB(上下文CTX){
this.context = CTX;
DBHelper =新DatabaseHelper(上下文);
}
私有静态类DatabaseHelper扩展SQLiteOpenHelper {
DatabaseHelper(上下文的背景下){
超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
}
@覆盖
公共无效的onCreate(SQLiteDatabase DB){
尝试 {
db.execSQL(CREATE_TABLE);
}赶上(的SQLException E){
e.printStackTrace();
}
}
@覆盖
公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
Log.w(TAG,从版本升级数据库+ oldVersion +到
+动态网页+,这将销毁所有旧数据);
db.execSQL(DROP TABLE IF EXISTS样本);
的onCreate(DB);
}
}
// ---开放的SQLite数据库---
公共SqliteDB的open()抛出的SQLException {
DB = DBHelper.getWritableDatabase();
回到这一点;
}
// ---密切的SQLite数据库---
公共无效的close(){
DBHelper.close();
}
// ---将数据插入的SQLite数据库---
众长刀片(字符串名称){
ContentValues initialValues =新ContentValues();
initialValues.put(KEY_NAME,姓名);
返回db.insert(TABLE_NAME,空,initialValues);
}
// ---删除所有数据,从表中的SQLite数据库---
公共无效用deleteAll(){
db.delete(TABLE_NAME,NULL,NULL);
}
// ---获取所有联系人的表中的SQLite数据库---
公共光标getAllData(){
返回db.query(TABLE_NAME,新的String [] {} KEY_NAME,
NULL,NULL,NULL,NULL,NULL);
}
}
接收JSON响应类
公共类DeptActivity延伸活动{
ArrayAdapter<字符串>适配器;
ListView控件listv;
上下文语境;
ArrayList的<字符串>数据;
SqliteDB sqlite的;
@覆盖
保护无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_dept);
sqlite的=新SqliteDB(DeptActivity.this);
setupActionBar();
数据=新的ArrayList<字符串>();
listv =(ListView控件)findViewById(R.id.lv_dept);
上下文=这一点;
适配器=新的ArrayAdapter<字符串>(这一点,android.R.layout.simple_list_item_1,数据);
listv.setAdapter(适配器);
Toast.makeText(这一点,Loading请稍候......,Toast.LENGTH_SHORT).show();
新AsyncLoadDeptDetails()执行();
}
公共类AsyncLoadDeptDetails扩展 AsyncTask的> { ArrayList的deptTable = NULL;
@覆盖
公众的ArrayList< DeptTable> doInBackground(空... PARAMS){
// TODO自动生成方法存根
RESTAPI API =新RESTAPI();
尝试 {
JSONObject的jsonObj = api.GetDepartmentDetails();
JSONParser分析器=新JSONParser();
Log.i(部门列表,jsonObj.toString());
deptTable = parser.parseDepartment(jsonObj);
sqlite的();
}赶上(例外五){
}
返回deptTable;
}
//方法插入SQLite中的数据JSON
私人无效源码(){
// TODO自动生成方法存根
sqlite.open();
的for(int i = 0; I< deptTable.size();我++){
sqlite.insert(deptTable.get(ⅰ)的ToString());
}
sqlite.close();
}
@覆盖
保护无效onPostExecute(ArrayList中< DeptTable>的结果){
// TODO自动生成方法存根
的for(int i = 0; I< result.size();我++){
data.add(result.get(ⅰ).getNo()++ result.get(ⅰ).getName());
}
adapter.notifyDataSetChanged();
Toast.makeText(背景下,加载完成,Toast.LENGTH_SHORT).show();
}
logcat的错误
错误插入name=com.example.db_client.DeptTable@b3e53870
android.database.sqlite.SQLiteException:没有这样的表:departmentList(code 1):在编制:INSERT INTO departmentList(名)VALUES(?)
在android.database.sqlite.SQLiteConnection.native prepareStatement(本机方法)
在android.database.sqlite.SQLiteConnection.acquire preparedStatement(SQLiteConnection.java:889)
在android.database.sqlite.SQLiteConnection。prepare(SQLiteConnection.java:500)
在android.database.sqlite.SQLiteSession。prepare(SQLiteSession.java:588)
在android.database.sqlite.SQLiteProgram< INIT>(SQLiteProgram.java:58)
在android.database.sqlite.SQLiteStatement< INIT>(SQLiteStatement.java:31)
在android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
在android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
在com.example.db_client.SqliteDB.insert(SqliteDB.java:73)
在com.example.db_client.DeptActivity $ AsyncLoadDeptDetails.sqlite(DeptActivity.java:91)
在com.example.db_client.DeptActivity $ AsyncLoadDeptDetails.doInBackground(DeptActivity.java:68)
在com.example.db_client.DeptActivity $ AsyncLoadDeptDetails.doInBackground(DeptActivity.java:1)
公共无效的onCreate(SQLiteDatabase DB){
尝试 {
db.execSQL(CREATE_TABLE);
}赶上(的SQLException E){
e.printStackTrace();
}
}
现在的问题是,你的 CREATE_TABLE
语句有错误,但你的的onCreate
函数燮pressed这错误,所以 SQLiteOpenHelper
假定它成功,并且数据库是可用的。
卸下尝试
/ 抓
,然后删除您的应用程序的数据(给力的onCreate
来再次执行)。
那么解决这个问题,你在错误信息出现错误。
I'm trying to create an app which gets data from sql server and shows in listview, but I also want to save the json in sqlite database. For this purpose I have created the following SqliteDB class but I'm confused about how to send json data to this class.
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);
}
}
class that receives json response
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();
}
public class AsyncLoadDeptDetails extends AsyncTask> { 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 Errors
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)
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
The problem is that your CREATE_TABLE
statement has an error, but your onCreate
function suppressed this error, so SQLiteOpenHelper
assumed that it succeeded, and that the database is usable.
Remove that try
/catch
, then remove your app's data (to force onCreate
to be executed again).
Then fix the error that you get in that error message.
这篇关于机器人:如何保存从SQL Server数据,Android的SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!