gpt4 book ai didi

java - 如何从非 Activity 类获取上下文

转载 作者:行者123 更新时间:2023-12-01 09:10:27 24 4
gpt4 key购买 nike

我在 Android Studio 中创建了一个游戏,现在我尝试将分数插入数据库。我在 SQL 中创建了一个脚本,可以很好地创建数据库,但现在我尝试插入信息,但没有上下文。

这是我的DBAdapter:

public class DBAdapter {

private SQLiteDatabase database;
private ScriptSQL dbHelper;
private String[] allColumns = {ScriptSQL.ID, ScriptSQL.PONTUACAO};

public DBAdapter(Context ctx) {
dbHelper = new ScriptSQL(ctx);
}

public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}

public void openRead() throws SQLException {
database = dbHelper.getReadableDatabase();
}

public void close() {
dbHelper.close();
}

public Score createScore(String pontuacao) {
ContentValues values = new ContentValues();
values.put(dbHelper.PONTUACAO, pontuacao);
long insertId = database.insert(dbHelper.TABLE_NAME, null, values);
// To show how to query
Cursor cursor = database.query(dbHelper.TABLE_NAME, allColumns, dbHelper.ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
return cursorToScore(cursor);
}

这是我试图获取上下文的非 Activity 类。

World.java

public class World {

static final int WORLD_WIDTH = 10; //largura
static final int WORLD_HEIGHT = 13; //altura
static final int SCORE_INCREMENT = 10; //incremento do score
static final float TICK_INITIAL = 0.8f; //velocidade inicial do jogo
static final float TICK_DECREMENT = 0.2f; //velocidade de decremento

public Dog dog;
public Elements element;
public boolean EndGame = false;
public int score = 0;

static int put_element = 0;
public List<Elements> elements = new ArrayList<Elements>();
Random random = new Random();
float timeTick = 0;
static float tick = TICK_INITIAL;

public World(){
dog = new Dog();
}

/*...*/

DBAdapter datasource;
private Context context;

public void update_database(){

datasource = new DBAdapter(context.getApplicationContext());

try {
datasource.open();
String point = Integer.toString(score);
Score c = datasource.createScore(point);
datasource.close();

}
catch (SQLException ex) { }

}

问题上线了:

datasource = new DBAdapter(context.getApplicationContext());

我也尝试这样做,但它给出了一个错误,因为这是一个非 Activity 类。

datasource = new DBAdapter(this);

我能做什么?

最佳答案

Context 存在于您的应用程序内部,并不属于特定的 Activity,但是您仍然需要访问它......

您可以将 Context 传递给非 Activity 类方法

public void update_database(Context yourAppContext){

datasource = new DBAdapter(yourAppContext);
//Other Stuff........
}

关于java - 如何从非 Activity 类获取上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40949057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com