-------This is my Database activity here i m creating database ----------
public void Database_Create(){
try{
db = openOrCreateDatabase(Environment.getExternalStorageDirectory()+"/TestExample/Test",MODE_PRIVATE,null);
}catch (Exception e){
e.printStackTrace();
}
}
------这是我的MainActivity ------------------
try{
Database dbs = new Database();
dbs.Database_Create();
Toast.makeText(dbs, "Data Ok", Toast.LENGTH_SHORT).show();
} catch (Exception e){
e.printStackTrace();
}
我在Database Activity中创建数据库,我想在MainActivity中调用Database_create()方法如何调用?我收到一个错误db object is null,我已经在manifest.xml文件中给出了权限
答案 0 :(得分:0)
首先看一下这个doc,
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class DBTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SQLiteDatabase myDB= null;
String TableName = "myTable";
String Data="";
/* Create a Database. */
try {
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (Field1 VARCHAR, Field2 INT(3));");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (Field1, Field2)"
+ " VALUES ('Saranga', 22);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
int Column1 = c.getColumnIndex("Field1");
int Column2 = c.getColumnIndex("Field2");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
int Age = c.getInt(Column2);
Data =Data +Name+"/"+Age+"\n";
}while(c.moveToNext());
}
TextView tv = new TextView(this);
tv.setText(Data);
setContentView(tv);
}
catch(Exception e) {
Log.e("Error", "Error", e);
} finally {
if (myDB != null)
myDB.close();
}
}
}
答案 1 :(得分:0)
您可以像这样创建数据库:
private SQLiteDatabase db;
private SQLiteDatabase db = openOrCreateDatabase(Environment.getExternalStorageDirectory()+"/TestExample/Test.db", Context.MODE_PRIVATE, null);
答案 2 :(得分:0)
这是在android sqlite中创建SQLite数据库的完整示例。我们需要使用SQLiteOpenHelper扩展一个类。并且需要创建一个构造函数来传递活动中的参数。
public class FlightsDatabase extends SQLiteOpenHelper {
private Context context;
public FlightsDatabase(Context context) {
super(context,"My_Datas",null,1);
this.context=context;
}
然后,我们需要声明数据库名称,当您希望在发布应用程序后对数据库进行一些更改时,可以使用2-3个选项来创建数据库和升级数据库版本。 然后,我们将表创建为:
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Flight (id INTEGER PRIMARY KEY AUTOINCREMENT,sr TEXT,today_date TEXT,imei TEXT,too TEXT,fromm TEXT,dept_date TEXT,status1 TEXT,file_url TEXT,plane_pic TEXT,plane_name TEXT,idd TEXT)");
}
然后您可以在数据库上应用搜索,检查数据和删除操作的操作。