我正在写一个应用程序,我想存储高分。我有它努力显示最终活动的高分。但是,我希望有一个高分榜活动来显示所有的高分。我这样做是在高分活动中,调用结束活动来返回高分,因此数据库不会改变。在运行调试之后,我看到它已经到了databasehandler但被getReadableDatabase()抓住了,说它无法在空对象引用上调用该方法。
这是我的高分方法(我没有包括整个事情,ifs是因为游戏有不同的困难)
public class highscores extends Activity {
TextView mode, score;
Button right, back;
int modenum;
end get=new end();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_highscores);
mode =(TextView)findViewById(R.id.scorebar);
score =(TextView)findViewById(R.id.score);
right =(Button)findViewById(R.id.button14);
back =(Button)findViewById(R.id.highscores);
mode.setText("Easy");
score.setText(get.datatostring(1));
modenum =1;
}
public void right(View view){
if(modenum==1) {
modenum = 2;
mode.setText("Hard");
score.setText(get.datatostring(2));
}else if(modenum==2) {
modenum = 3;
mode.setText("X-Mode");
score.setText(get.datatostring(3));
}else {
modenum = 1;
mode.setText("Easy");
score.setText(get.datatostring(1));
}
}
这是最后的方法
public String datatostring(int difficulty){
MyDBHandler db = new MyDBHandler(this, null,null,1);
return db.datatostring(difficulty);
}
这是在databasehandler
中 public String datatostring(int difficulty){
SQLiteDatabase db = getReadableDatabase();
String dbString = "";
String c;
if(difficulty==1)
c = COLUMN_SCORE;
else if(difficulty==2)
c = COLUMN_HARD;
else
c = COLUMN_X;
String query = "SELECT "+c+" FROM "+TABLE_SCORES;
Cursor cursor = db.rawQuery(query,null);
cursor.moveToFirst();
if(!cursor.isAfterLast()){
int index = cursor.getColumnIndex(c);
String value = cursor.getString(index);
if(value!=null){
dbString += cursor.getString(cursor.getColumnIndex(c));
}
}
db.close();
cursor.close();
return dbString;
}
答案 0 :(得分:0)
我建议使用SQLiteOpenHelper
来处理此问题。
你应该看到这个例子: Android Sqlite DB
希望有所帮助,我个人以这种方式工作。
另一种选择是使用som ORM,我建议使用GreenDao
,它的好处,让我们轻松处理这种行为。
问候。
答案 1 :(得分:0)
简短的回答是肯定的。
但是你看到你没有明确的连接概念。
android中的Bd是SQLite(推荐)总是在同一个路径上,你需要创建一个允许你管理和连接数据库的类。该类将是SQLiteOpenHelper
检查THIS
您可以将一次或多次连接到数据库,因为您需要活动A,B或活动。
重要的是定义处理程序以连接,关闭,向数据库发出请求。
答案 2 :(得分:0)
按照this教程创建并发且可伸缩的数据库
记住:
您应始终通过数据库适配器的一个实例(Singleton)进行数据库查询,否则在从不同类同时访问数据库时将面临许多问题。
使用SQLiteOpenHelper
类访问您的数据库。因为它为您提供了许多有用的功能,例如在发布带有架构更改的应用程序更新时升级用户的数据库。