我有一个数据库文件没有被读取的问题我已经在名为 mydb 的资产中添加了数据库文件,但是当我运行我的代码时它说它没有被定位。它正在调用这个 toast Toast.makeText(this, "No contact found", Toast.LENGTH_LONG).show(); 之所以调用它,是因为没有返回任何记录。我也知道它正在查找文件,因为没有 FileNotFoundException 异常。这是一个示例形式的 Android 应用程序开发书。
public class DatabaseActivity extends Activity {
/** Called when the activity is first created. */
TextView quest, response1, response2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView quest = (TextView) findViewById(R.id.quest);
try {
String destPath = "/data/data/" + getPackageName() + "/databases/MyDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DBAdapter db = new DBAdapter(this);
//---get a contact---
db.open();
Cursor c = db.getContact(2);
if (c.moveToFirst())
DisplayContact(c);
else
Toast.makeText(this, "No contact found", Toast.LENGTH_LONG).show();
db.close();
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
public void DisplayContact(Cursor c)
{
quest.setText(String.valueOf(c.getString(1)));
//quest.setText(String.valueOf("this is a text string"));
}
}
有没有更好的上传数据的方法。