[英]Android : Crash using sqlite database with cursor
我是android開發的新手,正在嘗試使用sqlite創建聯系人管理器列表,但是在使用游標訪問我的sqlite數據庫時遇到了麻煩。 我有2個活動,一個活動用於向數據庫添加新聯系人,另一個活動用於為數據庫讀取聯系人。
這是我的主要活動:
package com.example.contactmanager;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
private SQLiteDatabase sdb;
private TestDBOpenHelper tdb;
private ArrayList<String> al_strings;
private ArrayAdapter<String> aa_strings;
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tdb = new TestDBOpenHelper(this, "test.db", null, 1);
sdb = tdb.getReadableDatabase();
lv = (ListView) findViewById(R.id.lv);
al_strings = new ArrayList<String>();
aa_strings = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, al_strings);
lv.setAdapter(aa_strings);
String[] columns = { "ID", "NAME", "PHONE_NUMBER", "EMAIL" };
Cursor c = sdb.rawQuery("test", columns);
c.moveToFirst();
while (c.isAfterLast() == false) {
al_strings.add(c.getString(c.getColumnIndex("NAME")));
al_strings.add(c.getString(c.getColumnIndex("PHONE_NUMBER")));
al_strings.add(c.getString(c.getColumnIndex("EMAIL")));
c.moveToNext();
}
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent nextScreen = new Intent(getApplicationContext(),
AddContact.class);
startActivity(nextScreen);
}
});
}
public boolean listUpdate(Integer id, String name, String phone, String mail) {
SQLiteDatabase db = tdb.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", name);
cv.put("PHONE_NUMBER", phone);
cv.put("EMAIL", mail);
db.update("test", cv, "id = ? ", new String[] { Integer.toString(id) });
return true;
}
public Cursor getList() {
SQLiteDatabase sdb = tdb.getReadableDatabase();
// the columns that we wish to retrieve from the tables
String[] columns = { "ID", "NAME", "PHONE_NUMBER", "EMAIL" };
Cursor c = sdb.rawQuery("test.db", columns);
return c;
}
// overridden method that will clear out the contents of the database
/*@Override
protected void onDestroy() {
super.onDestroy();
// run a query that will delete all the rows in our database
String table = "test";
String where = null;
String where_args[] = null;
sdb.delete(table, where, where_args);
}*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
TestDBOpenHelper是我的用於初始化數據庫的類:
public class TestDBOpenHelper extends SQLiteOpenHelper {
// constructor for the class here we just map onto the constructor of the
// super class
public TestDBOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
// overridden method that is called when the database is to be created
public void onCreate(SQLiteDatabase db) {
// create the database
db.execSQL(create_table);
}
// overridden method that is called when the database is to be upgraded
// note in this example we simply reconstruct the database not caring for
// data loss
// ideally you should have a method for storing the data while
// you are reconstructing the database
public void onUpgrade(SQLiteDatabase db, int version_old, int version_new) {
// drop the tables and recreate them
db.execSQL(drop_table);
db.execSQL(create_table);
}
// a bunch of constant strings that will be needed to create and drop
// databases
private static final String create_table = "create table test ("
+ "ID integer primary key autoincrement, " + "NAME string,"
+ "PHONE_NUMBER string, " + "EMAIL string" + ");";
private static final String drop_table = "drop table test";
}
這是我的第二項活動,用於添加聯系人:
public class AddContact extends Activity {
EditText inputName;
EditText inputPhone;
EditText inputMail;
private TestDBOpenHelper tdb;
private MainActivity ma;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
tdb = new TestDBOpenHelper(this, "test.db", null, 1);
inputName = (EditText) findViewById(R.id.name);
inputPhone = (EditText) findViewById(R.id.ed_pho);
inputMail = (EditText) findViewById(R.id.ed_ema);
Button btnPrevScreen = (Button) findViewById(R.id.btn_add);
btnPrevScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle extras = getIntent().getExtras();
if(extras != null) {
int Value = extras.getInt("ID");
if(Value>0) {
if(ma.listUpdate(0, inputName.getText().toString(),
inputPhone.getText().toString(),
inputMail.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getApplicationContext(), "Not updated",
Toast.LENGTH_SHORT).show();
}
else {
if(addContact(inputName.getText().toString(),
inputPhone.getText().toString(),
inputMail.getText().toString())) {
Toast.makeText(getApplicationContext(), "Contact Added",
Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_SHORT).show();
}
Intent prevScreen = new Intent(getApplicationContext(), MainActivity.class);
startActivity(prevScreen);
}
}
});
}
public boolean addContact(String name, String phone, String mail) {
SQLiteDatabase sdb = tdb.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", name);
cv.put("PHONE_NUMBER", phone);
cv.put("EMAIL", mail);
sdb.insert("test", null, cv);
return true;
}
}
問題在這里,在我的MainActivity上:
Cursor c = sdb.rawQuery("test", columns);
當我對此發表評論時,我的應用程序“運行”(可以從nexus 5啟動它),我通過調試模式發現,正是這條線使其崩潰(我認為)。
這是LogCat:
02-27 17:59:04.408: E/SQLiteLog(28845): (1) near "test": syntax error 02-27 17:59:04.414: D/AndroidRuntime(28845): Shutting down VM 02-27 17:59:04.418: E/AndroidRuntime(28845): FATAL EXCEPTION: main 02-27 17:59:04.418: E/AndroidRuntime(28845): Process: com.example.contactmanager, PID: 28845 02-27 17:59:04.418: E/AndroidRuntime(28845): java.lang.RuntimeException: Unable to start activity
ComponentInfo {com.example.contactmanager / com.example.contactmanager.MainActivity}:android.database.sqlite.SQLiteException:在“ test”附近:語法錯誤(代碼1):,而在編譯時:test 02-27 17:59:04.418 :E / AndroidRuntime(28845):位於android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)02-27 17:59:04.418:E / AndroidRuntime(28845):位於android.app.ActivityThread.handleLaunchActivity(ActivityThread。 java:2360)02-27 17:59:04.418:E / AndroidRuntime(28845):at android.app.ActivityThread.access $ 800(ActivityThread.java:144)02-27 17:59:04.418:E / AndroidRuntime(28845) ):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278)02-27 17:59:04.418:E / AndroidRuntime(28845):在android.os.Handler.dispatchMessage(Handler.java:102) 02-27 17:59:04.418:E / AndroidRuntime(28845):在android.os.Looper.loop(Looper.java:135)02-27 17:59:04.418:E / AndroidRuntime(28845):在Android。 app.ActivityThread.main(ActivityThread.java:5221)02-27 17:59:04.418:E / AndroidRuntime(28845):at java.lang.reflect.Method.invoke(本機方法)02-27 17:59:04.418:E / AndroidRuntime(28845):at java.lang.reflect.Method.invoke(Method.java:372)02-27 17 :59:04.418:E / AndroidRuntime(28845):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899)02-27 17:59:04.418:E / AndroidRuntime(28845):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)02-27 17:59:04.418:E / AndroidRuntime(28845):原因:android.database.sqlite.SQLiteException:在“測試”附近:語法錯誤(代碼1):,編譯時:測試02-27 17:59:04.418:E / AndroidRuntime(28845):位於android.database.sqlite.SQLiteConnection.nativePrepareStatement(本地方法)02-27 17:59:04.418 :E / AndroidRuntime(28845):位於android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)02-27 17:59:04.418:E / AndroidRuntime(28845):位於android.database.sqlite.SQLiteConnection。 prepare(SQLiteConnection.java:500)02-27 17:59:04.418:E / AndroidRuntime(28845):位於android.database.sqlit e.SQLiteSession.prepare(SQLiteSession.java:588)02-27 17:59:04.418:E / AndroidRuntime(28845):位於android.database.sqlite.SQLiteProgram。(SQLiteProgram.java:58)02-27 17:59 :04.418:E / AndroidRuntime(28845):在android.database.sqlite.SQLiteQuery。(SQLiteQuery.java:37)02-27 17:59:04.418:E / AndroidRuntime(28845):在android.database.sqlite.SQLiteDirectCursorDriver .query(SQLiteDirectCursorDriver.java:44)02-27 17:59:04.418:E / AndroidRuntime(28845):at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)02-27 17:59:04.418 :E / AndroidRuntime(28845):位於android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)02-27 17:59:04.418:E / AndroidRuntime(28845):位於com.example.contactmanager.MainActivity。 onCreate(MainActivity.java:44)02-27 17:59:04.418:E / AndroidRuntime(28845):at android.app.Activity.performCreate(Activity.java:5933)02-27 17:59:04.418:E / AndroidRuntime(28845):位於android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105 )02-27 17:59:04.418:E / AndroidRuntime(28845):位於android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)02-27 17:59:04.418:E / AndroidRuntime(28845):..還有10個
我試圖解決這個問題已經好幾個小時了,但是我找不到辦法,任何幫助都是有福的。 這可能是我的一個愚蠢錯誤,請原諒我。
您需要編寫完整的SQL命令。 Cursor cursor = database.rawQuery("select * from exectable", null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.