-1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Eric
  • 1,547
  • 2
  • 18
  • 34

2 Answers2

1

You cannot pass a variable that was not initialize. On your second line of the function you declare the context variable but you don't assign any value to it.

The last line should be written in the constructor of VPAdapter. The constructor should get a context variable. When you call your constructor you probably want to use the application context, but you might send also an activity (Activity inherit from context) but this is usually not recommended (But it really depends on your code)

nheimann1
  • 2,348
  • 2
  • 21
  • 33
0

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.

Arvind Kanjariya
  • 2,089
  • 1
  • 18
  • 23
  • 'getApplicationContext()' is a function of context, which means that you need to have a context to do so. It works for you perfectly when you are in activity, since activity inherit from context. So this line cannot really help him. – nheimann1 Nov 07 '12 at 09:38
  • Than you can create constructor of your APAdapter and call that from your activity. – Arvind Kanjariya Nov 07 '12 at 09:42
  • well i put my DatabaseHandler db = new DatabaseHandler(context) inside VPAdpater constructor, thanks. – Eric Nov 07 '12 at 14:39