2012-06-11 4 views
0

Я все же действительно понимаю весь этот контекст, который мы нашли много в программировании для Android. поэтому я попытался создать функцию, чтобы удалить все мои таблицы, а вот мой частичный код:Проводящий контекст из неактивного

public class DBAdapter { 
     private static class DbHelper extends SQLiteOpenHelper { 
     private boolean databaseCreated = false; 
     public DbHelper(Context context) { 
      super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     } 

     public void deleteTables(){ 
     Log.d("DBAdapter","dlm drop tables pre"); 
     this.sqlDatabase.execSQL("DROP TABLE IF EXISTS ["+TABLE_TV+"];"); 
     this.sqlDatabase.execSQL("DROP TABLE IF EXISTS ["+TABLE_CAMERA+"];"); 
     this.sqlDatabase.execSQL("DROP TABLE IF EXISTS ["+TABLE_GPS+"];"); 
     } 
} 
} 

и ту часть, где я буду называть функция deleteTables

public class UpdateDatabase { 
    public void updateTable(String table,JSONObject jsonObject){ 
    DBAdapter db = new DBAdapter(this); 
     db.deleteTables(); 
    } 
} 

но, конечно, вернет ошибку, поскольку DBAdapter ожидает контекст. Открытый класс UpdateDatabase не является классом активности. Вызов DbAdapter db = новый DBAdapter (это) из класса активности будет работать только найти. Итак, как мне найти исправление для этой проблемы?

благодаря

+0

'updateTable' - это _static method_, у него нет' this' –

+0

ok, я исправил это и удалил static из updateTable, но все же, как я могу передать контекст в DBAdapter отсюда? – imin

ответ

2

Вы можете добавить конструктор к UpdateDatabase, который принимает Context и сохраняет его так, что он доступен для использования updateTable. Что-то вроде этого:

public class UpdateDatabase { 
    private final Context mContext; 

    public UpdateDatabase(Context context){ 
     mContext = context; 
    } 

    public void updateTable(String table,JSONObject jsonObject){ 
     DBAdapter db = new DBAdapter(mContext); 
     db.deleteTables(); 
    } 
} 

Теперь, когда вы делаете new UpdateDatabase() вам нужно будет сделать new UpdateDatabase(..context..) вместо этого. Если вы делаете это с Activity, вы можете сделать new UpdateDatabase(this).

0

привет выглядеть этот код ..

public class DbManager 
{ 
// the Activity or Application that is creating an object from this class. 
Context context; 
CustomSQLiteOpenHelper helper; 
// a reference to the database used by this application/object 
protected SQLiteDatabase db; 
private static DbManager INSTANCE; 
// These constants are specific to the database. 
protected final String DB_NAME = "yourDB"; 
protected final int DB_VERSION = 1; 



public DbManager(Context context) 
{ 
    this.context = context; 
    // create or open the database 
    helper = new CustomSQLiteOpenHelper(context); 
    this.db = helper.getWritableDatabase(); 
} 
public static DbManager getInstance(Context context){ 
    if(INSTANCE == null)INSTANCE = new DbManager(context); 
    return INSTANCE; 
    } 
public void db_Close() 
{ 
    if(helper!=null){ 
     helper.close(); 
    } 
    this.db.close(); 
} 



private class CustomSQLiteOpenHelper extends SQLiteOpenHelper 
{ 

    public CustomSQLiteOpenHelper(Context context) 
    { 
     super(context, DB_NAME, null, DB_VERSION); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) 
    { 
     // This string is used to create the database. 
     // execute the query string to the database. 
     //db.execSQL(newTableQueryString); 
     Log.i("DataBaseManager", "Create Table"); 
    } 


    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    { 
     // NOTHING TO DO HERE. THIS IS THE ORIGINAL DATABASE VERSION. 
     // OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THE DATABASE. 
    } 

} 
} 

// Inherit the DbManager Class 
public class DataCollection extends DbManager { 

public DataCollection(Context context){ 
     super(context); 
} 
    public void deleteTable(String TABLE_NAME){ 
    try {db.execSQL("DROP TABLE "+TABLE_NAME);}//.delete(TABLE_NAME, null, null);} 
    catch (Exception e){ 
     Log.e("DB ERROR", e.toString()); 
     e.printStackTrace(); 
    } 
} 
Смежные вопросы