非活动类中的上下文

时间:2016-01-19 16:05:32

标签: android database class

我需要在非活动类中使用数据库处理程序,但为此我需要上下文而我无法得到它。 我试过用这个但没有运气,

protected Context context;

    public Example(Context context){
        this.context = context.getApplicationContext();
    }

它总是抛出这个错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference

编辑:

public class Telnet extends AsyncTask<Void, Void, Void> {
   wifiHistoryDatabaseHandler wifihist;

    @Override
    protected Void doInBackground(Void... params) {


        wifihist = new wifiHistoryDatabaseHandler(context);
 }

WifiHistoryDatabaseHandler:

public class wifiHistoryDatabaseHandler  extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "information_db_232";
    // Contacts table name
    private static final String TABLE_CONTACTS = "wifi_history";

    public static final String ID = "id";
    public static final String message = "message";
    public static final String message_source = "message_source";
    public static final String time = "time";


    public wifiHistoryDatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE =  "CREATE TABLE "
                + TABLE_CONTACTS + "( " + ID
                + " INTEGER PRIMARY KEY,"+message+","+message_source+","+time+" );";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);
    }


    //add line
    public void addLine(wifiHisotryClass info) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(message, info.get_message());
        values.put(message_source, info.get_message_source());
        values.put(time, info.get_time());



        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }


    // Getting single contact
    public wifiHisotryClass getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[]{ID
                        ,message,message_source, time}, ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        wifiHisotryClass info = new wifiHisotryClass(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2), cursor.getString(3));

        // return info
        return info;
    }

    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(countQuery, null);
        int num = cursor.getCount();
        cursor.close();

        // return count
        return num;
    }


    // Updating single contact
    public int updateContact(wifiHisotryClass info) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(message, info.get_message());
        values.put(message_source, info.get_message_source());
        values.put(time, info.get_time());

        // updating row
        return db.update(TABLE_CONTACTS, values, ID + " = ?",
                new String[] { String.valueOf(info.getID()) });
    }


    // Deleting single contact
    public void deleteContact(Info info) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, ID + " = ?",
                new String[]{String.valueOf(info.getID())});
        db.close();
    }

    void deleteAll()
    {
        SQLiteDatabase db= this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, null, null);

    }


}

3 个答案:

答案 0 :(得分:0)

public Example(Context context){
        this.context = context.getApplicationContext();
    }

为什么呢?使用

this.context = context;

代替。

 wifihist = new wifiHistoryDatabaseHandler(getActivity());

telnet类中的上下文变量为null。

您可以考虑直接在Telnet异步任务的构造函数中传递上下文

public Telnet(Context c)
{ 
   mContext = c;
}

答案 1 :(得分:0)

将wifiHistoryDatabaseHandler类的对象声明移到您尝试访问它的函数中,而不是全局声明它。

答案 2 :(得分:0)

您应该将Application用作单例类

public class MyApplication extends Application {

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getContext() {
        return mContext;
    }
}

不要忘记在清单文件中声明应用程序:

<application
    android:name=".MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name" >

通过这种方式,您可以使用MyApplication.getContext()

从应用的任何非活动类中获取应用上下文

回答:https://stackoverflow.com/a/21819009/4848308