我是Android的新开发者。我需要编写一个简单的hello-world应用程序,在屏幕上显示有关应用程序所连接的数据库的一些数据。 这是我的尝试,但它在“选择或显示”部分崩溃。 它由两个文件组成:Main和DataBaseHelper。
主:
package com.SQLearning;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloTestSQLActivity extends Activity {
DatabaseHelper dbHelper;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
int seats = dbHelper.getSeats("2");
TextView tv = new TextView(this);
setContentView(tv);
tv.setText( "My first Android App: This is a Hello World Test..." +
"Database connection in progress..." +
"Table 2 has "+seats);
}
}
DataBaseHelper:
package com.SQLearning;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
static final String dbName="demoDB";
static final String tablesTable="Tables";
static final String colNum="TableNum";
static final String colSeats="NumSeats";
static final String viewTables="ViewTables";
public DatabaseHelper(Context context) {
super(context, dbName, null,2);
}
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+tablesTable+" ("+colNum+ " INTEGER PRIMARY KEY , "+
colSeats+ " INTEGER)");
db.execSQL("CREATE VIEW "+viewTables+
" AS SELECT "+tablesTable+"."+colNum+" AS _id,"+
" "+tablesTable+"."+colSeats+","+
" FROM "+tablesTable);
//Inserts pre-defined departments
insertTableRecords();
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+tablesTable);
db.execSQL("DROP VIEW IF EXISTS "+viewTables);
onCreate(db);
}
public void insertTableRecords() {
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colNum, 1);
cv.put(colSeats, 3);
db.insert(tablesTable, colNum, cv);
cv.put(colNum, 2);
cv.put(colSeats, 6);
db.insert(tablesTable, colNum, cv);
cv.put(colNum, 3);
cv.put(colSeats, 5);
db.insert(tablesTable, colNum, cv);
cv.put(colNum, 4);
cv.put(colSeats, 2);
db.insert(tablesTable, colNum, cv);
db.close();
}
public int getSeats(String tablenum)
{
SQLiteDatabase db=this.getReadableDatabase();
String[] args = new String[] {"1"};
Cursor cur = db.rawQuery(" SELECT "+colSeats+" FROM "+tablesTable+" WHERE "+colNum+"=? ", args);
cur.moveToFirst();
db.close();
//return cur.getInt(cur.getColumnIndex(colSeats));
return cur.getInt(0);
}
}
提前致谢。
答案 0 :(得分:0)
我认为阿迪尔想说出这件事......
----------
/**open the db**/
----------
DbHelper = new DatabaseHelper(context);
db = mDbHelper.getWritableDatabase();
/**Closes the OLQ Database*/
public void closeOLQ()
{
mDbHelper.close();
}