0
我想使用單例類來創建這個數據庫,因爲我需要它爲應用程序中的每個活動打開。我一直從任一「getFilesDir」得到一個空指針錯誤或「如果(例如== NULL)調用,並且因爲我不是那麼熟悉了Android編程我不知道是怎麼回事。設置db4o數據庫的麻煩
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);
}
一直試圖讓過去幾周該數據庫的工作都無濟於事。任何幫助或指導將不勝感激。
在偶數處理程序使用該調用的唯一麻煩的是,我們得到了一個靜態參考從活動中使用getApplicationContext()時出現非靜態方法錯誤。 – user1799107
能夠使用 'AnotherTest.getInstance(getBaseContext())storePlay(新野);' 而截至目前,從一些小的快速測試我做的工作。再次,非常感謝幫助和解釋發生了什麼問題,我非常感謝! – user1799107