-3

I need to use a database handler inside a non activity class but for that I need the context and I can't get it. I have tried using this but no luck,

protected Context context;

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

It always throws this error:

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

EDIT:

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

    }


}
scottbear
  • 155
  • 1
  • 2
  • 10

3 Answers3

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

why? use

this.context = context;

instead.

or

 wifihist = new wifiHistoryDatabaseHandler(getActivity());

The context variable in telnet class is null.

You can consider to pass context directly in the constructor of Telnet async task

public Telnet(Context c)
{ 
   mContext = c;
}
Alessandro Verona
  • 1,157
  • 9
  • 23
0

Move wifiHistoryDatabaseHandler class's object declaration inside the function where you're trying to access it rather than declaring it globally.

Ramkishore V S
  • 124
  • 1
  • 8
0

You should use Application as a singleton class

public class MyApplication extends Application {

    private static Context mContext;

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

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

Don't forget to declare the application in your manifest file:

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

With this way you can get application context from any non activity class of your app using MyApplication.getContext()

Answer from: https://stackoverflow.com/a/21819009/4848308

Community
  • 1
  • 1
Gueorgui Obregon
  • 5,077
  • 3
  • 33
  • 57