我正在尝试使用单例类来创建此数据库,因为我需要为应用程序中的每个活动打开它。我不断从“getFilesDir”或“if(instance == null) 调用中收到空指针错误,并且由于我对 Android 编程不太熟悉,所以我不确定发生了什么。
package com.database;
import java.io.File;
import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
import com.businessclasses.Field;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.AndroidSupport;
import com.db4o.config.EmbeddedConfiguration;
public final class anotherTest extends Application {
private static ObjectContainer playsDB;
private static ObjectContainer gamePlanDB;
private anotherTest instance;
public anotherTest(){
final EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
config.common().add(new AndroidSupport());
//instance.getFilesDir().getPath()
new File(getFilesDir().getPath(), "/PlaysDB.db4o").delete();
Log.d("db", "" + instance.getFilesDir().getPath());
//getFilesDir().getPath();
//String appPath = "/data/data/PlaysDB/database";
playsDB = Db4oEmbedded.openFile(config, getFilesDir().getPath() + "/PlaysDB.db4o");
//File test = new File(appPath + "/PlaysDB.db4o");
//if(test != null){
// Log.d("db", "file was created");
// Log.d("db", "path >> " + test.getAbsolutePath());
//test.delete();
//}
//playsDB = Db4oEmbedded.openFile(config, appPath + "/PlaysDB.db4o");
}
public synchronized anotherTest getInstance(){
if(instance == null){
instance = new anotherTest();
}
return instance;
}
public void storePlay(Field field){
if(field != null){
if(playsDB == null){
Log.d("db", "database is null");
}
playsDB.store(field);
playsDB.commit();
Log.d("added play", "play added to db");
}
else{
Log.e("field input null", "play not added to db");
}
}
}
这是我参加其中一项活动的电话。
public void onClick(View v) {
String formation = playFormation.getText().toString();
String name = playName.getText().toString();
String type = playType.getSelectedItem().toString();
//TODO:send to database
Field newField = new Field();
newField.setPlayName(name);
newField.setPlayType(type);
anotherTest temp = new anotherTest();
temp.getInstance().storePlay(newField);
}
过去几周一直试图让这个数据库工作,但无济于事。任何帮助或指导将不胜感激。