Search code examples
androidconstructorhandlerandroid-contextsqliteopenhelper

Trouble with Constructor with helper


VPAdapter.java

public class VPAdapter extends PagerAdapter 
{     
     public static String[] titles;
     public final Context context;
     public int[] scrollPosition;
     JSONArray categories = null; 
     JSONArray newstype = null; 
     JSONObject json;
     DatabaseHandler db = new DatabaseHandler(context)//error:The blank final field context may not have been initialized
...
}

DatabaseHandler.java

public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

On VPAdapter.java I wanted to access DatabaseHandler anywhere, but there is problem with the constructor. What is the proper way I should write them?


Solution

  • Because your Context is null first initialize your context than you can pass that context to your database handler constructor.

    Context context = getApplicationContext();
    

    Or try below code

    For example initialize your Context with your activity context.

    Create constructor of your APAdapter class and call that constructor from your activity. Same way as you create for database handler.

    public APAdapter(Context context) {
    this.context = context;
    }
    

    than pass that context to your database handler.