我正在努力解决一个奇怪的问题。我编写了一个代码来创建数据库、创建表并插入一行并使用游标检索该行。
我的问题是当我第一次运行数据库创建并且表也创建但未插入行时。所以当我开始调试控制处理getWritabledatabase并且它没有移动到Oncreate时,我尝试调试应用程序。下面是我的代码。
主要活动:
package com.example.testdb;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Database d=new Database(this);
}
@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;
}
}
数据库类
package com.example.testdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
public class Database extends SQLiteOpenHelper{
String Tablename = "Table1";
private String Column1 = "RegionID";
private String Column2 = "RegionName";
private String Column3 = "Currency";
SQLiteDatabase db;
public Database(Context context) {
super(context, "Test", null, 2);
this.getWritableDatabase();
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try{
final String r_Table = "CREATE TABLE " + Tablename + " (" + Column1+ " INTEGER PRIMARY KEY , " + Column2 + " TEXT, " + Column3 + " Text) ";
db.execSQL(r_Table);
ContentValues cv=new ContentValues();
cv.put(Column1, 1);
cv.put(Column2, "US");
cv.put(Column3, "Dollar");
db.insert(r_Table, null, cv);
}
catch(Exception e){
System.out.println(e.getMessage());
}
Cursor c=db.rawQuery("Select * from Table1", null);
if (c != null ) {
if (c.moveToFirst()) {
//Toast.makeText(new MainActivity().getApplicationContext(), c.getCount(), Toast.LENGTH_LONG).show();
System.out.println("Rows are:"+c.getCount());
}
}
c.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
谁能帮我解决这个问题,因为我在过去一周对此感到震惊。
在此先感谢西瓦