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?
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)
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.
Related
I have a little concern about how I handle my database in my apps, here is basically what I do:
I have a custom class extending SQLiteOpenHelper that handles all the transactions with the DB.
In my app, I have one single Activity and several Fragments that are created, deleted, hidden or shown during the process.
In every Fragment where I need to modify or access data from the DB, I declare a static variable:
private static DatabaseHandler mDB;
And I initialize it this way on the onCreate() methods:
mDB = DatabaseHandler.getInstance(getActivity());
All this is working, my concern is about the variable itself, is it a good idea to declare it as a static variable in all my custom fragment classes?
I also use the same way a class containing the main parameters of the app using mParams = Parameters.getInstance(getActivity());, should I also declare it as static?
I want to avoid memory leaks and NPE but I am not sure what is the right way to handle that.
FYI, the beginning of my DatabaseHandler class:
public class DatabaseHandler extends SQLiteOpenHelper {
private static DatabaseHandler sInstance = null;
(...)
private Resources mResources;
public static DatabaseHandler getInstance(Context context) {
if (sInstance == null) {
sInstance = new DatabaseHandler(context);
}
return sInstance;
}
private DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mResources = context.getResources();
}
(...)
Thank you
I normally create a SQLiteDatabase static instance in my Application class and access across the app.
So , I have a custom class which returns SQLiteDatabase instance on application create.
This is my Application class
public class MainApplication extends Application {
private static SQLiteDatabase mSQLiteDatabase = null;
#Override
public void onCreate(){
super.onCreate();
SQLiteAsyncTask sqLiteAsyncTask = new SQLiteAsyncTask(getApplicationContext());
mSQLiteDatabase = (SQLiteDatabase) sqLiteAsyncTask.loadInBackground();
}
// method to get the sqlite db instance
public SQLiteDatabase getSQLiteInstance(){
return mSQLiteDatabase;
}
}
Now you can get the SQLiteDatabase instance from Activity or Fragment , by
MainApplication.getSQLiteInstance()
I have a Main class and another two classes named WebServicesClass and DynamicHeightAdpater.
I am creating an instance of DynamicHeightAdpater in WebServicesClass for which I need the context of MainActivity but I am not sure how to point it. The way by which I am calling throws a NullPointerException.
CODE :
MainActivity :
static Context context;
context = this.context;
WebServicesClass :
new DynamicHeightAdapter(MainActivity.context, 1, rowItems);
But it throws a null pointer exception and I am sure that it is due to the context cause I tried to print it and it threw NullPointer.
I would suggest you to take a look at the Android application class. You can store context there and retrieve it, when needed:
public class TestApplication extends Application {
private static Context mAppContext;
#Override
public void onCreate() {
super.onCreate();
mAppContext = getApplicationContext();
}
/**
* Returns the application's context. Useful for classes that need a Context
* but don't inherently have one.
*
* #return application context
*/
public static Context getAppContext() {
return mAppContext;
}
I suggest passing the Context to the WebServicesClass object in it's constructor, and having a member variable to keep it... something like
public class WebServicesClass
{
private Context mContext;
...
public WebServicesClass(Context c) // constructor
{
mContext = c;
}
void someOtherFunction()
{
new DynamicHeightAdapter(mContext, 1, rowItems);
}
}
I'd like to get my string-array without extending Activity in my custom class. Is there a way to do this?
String[] foo_array = getResources().getStringArray(R.array.foo_array); will not work without extending Activity, so I need a work-around.
Pass the context to the constructor of custom class and use the same
new CustomClass(ActivityName.this);
Then
Context mContext;
public CustomClass(Context context)
{
mContext = context;
}
use the context
String[] foo_array = mContext.getResources().getStringArray(R.array.foo_array);
Also keep in mind
Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html
Also check this
android getResources() from non-Activity class
Edit:
Change this
public class CustomClass(Context context)
{
}
To
public class CustomClass
{
Context mContext;
public CustomClass(Context context) // constructor
{
mContext = context;
}
}
try this,
Context context=getApplicationContext();
String[] foo_array = context.getResources().getStringArray(R.array.foo_array);
And, do not use Activity Context as that is tied to the Activity life cycle.
Update,
getApplicationContext() is from Context class. That means any thing extended Context have this method. This also means you will be able to use this from service or from other resources.
But, if you custom class do not extend Activity/context, you have to pass Context as parameter to use getApplicationContext()
if you declare your activity like this
myMethod(Activity activity) //this is bad
Bud if it is like following,
myMethod(Context context) //this is ok
but from above declaration do not pass Activity or Service Context as they have own life cycle. instead you will use getApplicationContext()
You need pass the Activity context to the Custom class.
private Context context;
public CustomClass(Context context)
{
this.context=context;
}
if you use numberpicker and pass String from sring xml then use this
np_Basic_Hight.setMinValue(0);
np_Basic_Hight.setMaxValue(71);
np_Basic_Hight.setDisplayedValues(getContext().getResources().getStringArray(R.array.hieght));
my question is simple. How can i get access to the string value in res/values/string.xlm in a extends SQLiteOpenHelper because getString method is use with an Activity ?
u can get context object through constructor.
class DatabaseHelper extends SQLiteOpenHelper {
private Context mContext;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
}
Try
Receive Context in your SQLiteOpenHelper class and then use Context like
context.getResources().getString(R.string.yourStringNameFromStrings);
You need a reference to Context. The constructor of SQLiteOpenHelper accepts a context, you can save it in a local variable. If c is context variable, and myString is the name of string resource in strings.xml, then you can get string value as:
C.getString(R.string.myString);
I have class MyCustomAdapter
public class MyCustomAdapter extends SimpleCursorAdapter{
}
I have other class called DbAdapter, where I have functions with sql query. I'd like to access functions from class MyCustomAdapter
DbAdapter db and next I have to add
db = new DbAdapter(this)
but it doesnt work. I tried
Contex contex
db = new DbAdapter(contex) but then I have java.lang.NullPointerException
Is any way to access my DbAdapter within MyCustomAdapter?
Make your MyCustomAdapter-class accept a Context-object as a parameter:
public class MyCustomAdapter extends SimpleCursorAdapter{
private final Context context;
public MyCustomAdapter(Context c){
this.context = c;
}
}
In the calling activity, you can then simply pass this for the context.
You're getting this error because the DVM tries to invoke a SimpleCursorAdapter(Context)-constructor, which does not exist.
The solution to your problem is either explicitly calling a valid constructor of SimpleCursorAdapter by using super(...) or making the MyCursorAdapter-constructor accept the same parameters as one of the SimpleCursorAdapter-constructors.
What way to go relies on what you want to do with your Cursor-adapter. If you have constant values for certain constructor-arguments, you can use those, if you don't, you'll need to include them in your MyCursorAdapter-constructor.
As an example, this assumes you don't have constant values for any constructor-argument:
public class MyCustomAdapter extends SimpleCursorAdapter{
private final Context context;
public MyCustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to){
super(Context context, int layout, Cursor c, String[] from, int[] to); // Call the super-
// classes constructor
this.context = context; // Save the context for further use
}
}
Some further information on this might be found here.