在这个例子中,我想要一个包含两个表(SentMessages 和 SavedMessages)的数据库(Databse1.db)。正在创建数据库,但未创建表。我已经在外部创建了数据库和表,并将其复制到 assets 文件夹中。从那里以编程方式将其复制到 data/data/....... 谁能帮我吗?
这是我的 DatabasesActivity.java 类
package com.example.messagingapp2;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class DatabasesActivity extends Activity
{
EditText text1,text2;
String str1,str2;
DBAdapter db;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (EditText)findViewById(R.id.widget33);
text2 = (EditText)findViewById(R.id.widget36);
db = new DBAdapter(this);
db.createDatabase();
}
public void OnClickSend(View v)
{
str1=text1.getText().toString();
str2=text2.getText().toString();
db.open();
long id = db.insertContact1(str1,str2);
db.close();
}
public void OnClickSave(View v)
{
str1=text1.getText().toString();
str2=text2.getText().toString();
db.open();
long id = db.insertContact2(str1,str2);
db.close();
}
这是我的 DBAdapter.java 类,它有 DatabaseHelper 作为内部类
package com.example.messagingapp2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter
{
protected static final String TAG = "DataAdapter";
private final Context context;
private SQLiteDatabase db;
DatabaseHelper DBHelper;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public DBAdapter createDatabase() throws SQLException
{
try
{
DBHelper.createDataBase();
Log.e(TAG, "CreateDatabase Succesful");
}
catch (IOException e)
{
Log.e(TAG, e.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}
public DBAdapter open() throws SQLException
{
try
{
DBHelper.openDataBase();
DBHelper.close();
db = DBHelper.getReadableDatabase();
}
catch (SQLException e)
{
Log.e(TAG, "open >>"+ e.toString());
throw e;
}
return this;
}
public void close()
{
DBHelper.close();
}
public long insertContact1(String too, String message)
{
ContentValues initialValues = new ContentValues();
initialValues.put("too", too); //Adds a value to the set.
initialValues.put("message", message);
return db.insert("SentMessages", null, initialValues);
}
public long insertContact2(String too, String message)
{
ContentValues initialValues = new ContentValues();
initialValues.put("too", too); //Adds a value to the set.
initialValues.put("message", message);
return db.insert("SavedMessages", null, initialValues);
}
}