如何从非活动类中获取Context

时间:2016-12-03 14:54:21

标签: java android

我在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);
}

这是我尝试获取上下文的非活动类。

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());

我也尝试过这样做,但它会出错,因为这是一个非活动类。

datasource = new DBAdapter(this);

我该怎么办?

2 个答案:

答案 0 :(得分:1)

Context存在于您的应用程序中,并且不属于特定的活动,但您仍然需要访问它....

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

public void update_database(Context yourAppContext){

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

答案 1 :(得分:0)

在非活动类的构造函数中传递上下文。在初始化非活动类传递上下文时