I made nonActivity class, and I use there other nonActivity Database class. When I call method from 1st class I have Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Here is a fragment of my code of both classes:
DataBase.java
public DataBase(Context context) {
super(context, DATABASE_NAME, null, TABLE_VERSION);
}
and ObliczPodatki.java
public class ObliczPodatki extends Application
.
.
.
myDb = new DataBase(this.getApplicationContext());
and the full error message:
Process: com.example.nadgraniav01, PID: 11274
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:116)
at com.example.nadgraniav01.ObliczPodatki.obliczPodatki(ObliczPodatki.java:43)
at com.example.nadgraniav01.DodajNadgranieActivity$2.onClick(DodajNadgranieActivity.java:99)
at android.view.View.performClick(View.java:6669)
at android.view.View.performClickInternal(View.java:6638)
at android.view.View.access$3100(View.java:789)
at android.view.View$PerformClick.run(View.java:26145)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
if I use this instead of this.getApplicationContext() I am getting following erroe
Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
Try this then:
#Override
public void onCreate() {
super.onCreate()
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
....rest of db calls..
}
Use:
myDb = new DataBase(getApplicationContext());
Or,
myDb = new DataBase(Activityname.this);
getApplicationContext is not the context that you should use,
Use this instead
myDb = new DataBase(this);
You have to initialise myDb variable in onCreate() method of ObliczPodatki class.
myDb = new DataBase(getApplicationContext());
Related
The problem occurs when I call putString to SharedPreference.
My program is first run through TileService which runs a ForegroundService then from ForegroundService opens an Activity and in this Activity I call putString to a SharedPreference.
How to make it work perfectly?
TileService
...
#Override
public void onClick()
{
super.onClick();
Intent intent = new Intent(mContext,AdzanService.class);
if(mTileEnabled)
intent.setAction("STOP_SERVICE");
else
intent.setAction("START_SERVICE");
startForegroundService(intent);
mTileEnabled = !mTileEnabled;
}
...
Service
...
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent.getAction().equals("STOP_SERVICE"))
{
stopForeground(true);
stopSelf();
}
...
Activity
...
private void save(){
mEditor.putString("setting_location",((EditText)findViewById(R.id.setting_location)).getText().toString());
mEditor.putString("setting_times",((RadioButton)findViewById(((RadioGroup)findViewById(R.id.setting_times)).getCheckedRadioButtonId())).getTag().toString());
mEditor.apply();
}
...
Error
java.lang.RuntimeException: Unable to start service in.blackant.adzan.AdzanService#873299c with null: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3722)
at android.app.ActivityThread.access$1600(ActivityThread.java:198)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1686)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6693)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getAction()' on a null object reference
at in.blackant.adzan.AdzanService.onStartCommand(AdzanService.java:97)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3703)
... 8 more
As the error message states, the Intent in your service class is null when you call intent.getAction()
Intent is nullable here according to the docs
The Intent supplied to Context.startService(Intent), as given. This may be null if the service is being restarted after its process has gone away, and it had previously returned anything except START_STICKY_COMPATIBILITY.
Adding a null check before you check getAction() will fix the crash, but you might want to look into why your service is being restarted
TinyDb class is here
im using it simply by default codes like : TinyDB tinyDB = new TinyDB(MyActivity.this); and tinyDB.putInt("hadi" , 10);
but im getting an error that i cant understand . it say tinyDB is null object reference . you can see the error below :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.ahmadi.TinyDB.TinyDB.putInt(java.lang.String, int)' on a null object reference
You have to create Object of Your TinyDB class like :-
TinyDB tinyDB = new TinyDB();
You should properly initiate your TinyDB before using it!
For Example in Activity:
TinyDB tinyDB = new TinyDB(this);
tinyDB.putInt("hadi" , 10);
or in Fragment:
TinyDB tinyDB = new TinyDB(getContext());
tinyDB.putInt("hadi" , 10);
TinyDB is just a simple wrapper around SharedPreferences so it is important that you provide a valid Context to it to initiate SharedPreferences
You are getting error because you are passing context before Oncreate just pass the context after oncreate donot make it global variable.
I'm about to write a small app where I have pretty much all the data stored in a custom array which contains of list views. I don't wanna save the data in a different form. This array I like to save in shared preferences. I head a look for other answered questions and tried different ways but none of then worked for me.
In the main activity, I have two small methods:
public class MainActivity extends AppCompatActivity {
public static ArrayList<Item> items = new ArrayList<Item>();
SharedPreferences mPrefs = getBaseContext().getSharedPreferences("KEY12", Context.MODE_PRIVATE);
Gson gson = new Gson();
[...]
protected void savePrefs() {
SharedPreferences.Editor editor = mPrefs.edit();
String json = gson.toJson(items);
System.out.println(json);
editor.putString("items_prefs", json);
editor.commit();
}
protected void loadPrefs() {
String empty_list = gson.toJson(new ArrayList<Item>());
items = gson.fromJson(mPrefs.getString("KEY12", empty_list),
new TypeToken<ArrayList<Item>>() {}.getType());
}
}
I'm calling the loadPrefs(); method in onCreate and savePrefs(); in onResume so everytime when I come back to the main activity, the preferences should be updated.
The error that I get is:
FATAL EXCEPTION: main
Process: com.example.android.calc123, PID: 30579
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.calc123/com.example.android.calc123.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at com.example.android.calc123.MainActivity.(MainActivity.java:61)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
How can I fix this problem or - asking in a different way - what am I doing wrong when dealing with shared preferences?
As the error log say you call getSharedPreferences in a null pointer (getBaseContext)
put in OnCreate mPrefs = getBaseContext().getSharedPreferences("KEY12", Context.MODE_PRIVATE);
I am getting the following line in LogCat that seems to point to a null dbHelper when opening my SQLite DB.
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
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.---.---.GasDataSource.open(GasDataSource.java:29)
at com.---.---.Vehicle.<init>(Vehicle.java:33)
at com.---.---.GasFragment$1$3.onClick(GasFragment.java:212)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Here is the chain of code listed in the Stacktrace (it references three lines):
Instantiate a new Object:
Vehicle v = new Vehicle(getActivity(), vId); // GasFragment.java:212
Open the Datasource inside the Object to load existing properties
public Vehicle(Context mContext, int vehicleId) {
GasDataSource datasource = new GasDataSource(mContext);
datasource.open(); // Vehicle.java:33
Do the actual Open method
database = dbHelper.getWritableDatabase(); // GasDataSource.java:29
Supplemental code: GasDataSource constructor:
public GasDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
I don't understand how dbHelper can be null. The only thing I can think of was the context was null OR thedatabase was closed already because this happened as the app was in the background for a long time and when I opened it up and hit the 'save' button in the Activity (which triggers this code in part).
Can someone possibly identify the cause, if not, what the best way to at least do a null check here? it seems weird to do it on this line (I have never seen it done before in examples): dbHelper.getWritableDatabase();
When I attempt to call the method loadUserList() from another class, I get the following error:
Attempt to invoke virtual method android.content.res.Resources
android.content.Context.getResources() on a null object reference
This is my loadUserList method
public void loadUserList()
{
final ProgressDialog dia = ProgressDialog.show(this, null, getString(R.string.alert_loading));
ParseQuery<ParseObject> query = ParseQuery.getQuery("Chat_User");
query.whereEqualTo("receiver", ParseUser.getCurrentUser());
query.include("sender");
query.findInBackground(new FindCallback<ParseObject>()
{
#Override
public void done(List<ParseObject> li, ParseException e)
{
dia.dismiss();
if (li != null)
{
if (li.size() == 0)
Toast.makeText(com.yarnyard.UserList.this, R.string.msg_no_user_found,
Toast.LENGTH_SHORT).show();
uList = new ArrayList<ParseObject>(li);
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new UserAdapter());
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3)
{
loadUserList();
/*startActivity(new Intent(com.yarnyard.UserList.this, Chat.class)
.putExtra(Const.EXTRA_DATA, uList.get(pos).getUsername()));*/
}
});
}
else
{
Utils.showDialog(
com.yarnyard.UserList.this,
getString(R.string.err_users) + " "
+ e.getMessage());
e.printStackTrace();
}
}
});
}
This is how I am calling it
public void done(ParseException e)
{
UserList UserList = new UserList();
UserList.loadUserList();
}
My error log
07-30 14:14:56.219 13383-13383/com.anonimv2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.anonimv2, PID: 13383
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:85)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at android.content.Context.getString(Context.java:376)
at com.yarnyard.UserList.loadUserList(UserList.java:96)
at com.yarnyard.custom.CustomActivity.onOptionsItemSelected(CustomActivity.java:116)
at android.app.Activity.onMenuItemSelected(Activity.java:2882)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1131)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at android.widget.ActionMenuView.invokeItem(ActionMenuView.java:587)
at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:141)
at android.view.View.performClick(View.java:4832)
at android.view.View$PerformClick.run(View.java:19839)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5321)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
Any advice would be much appreciated.
Normal, non-static methods are called on objects, not on classes. This is a fine point that you really need to learn before using object oriented languages. Only then you will see, in practice, how you can connect objects by passing references.
The UserList objects that you construct in the done method is not the one you want to call, it's just an empty, uninitialized shell.
As I understand, you extend UserList from Context, right?
Then keep in mind that in Android never initial a Context object by yourself, it's framework's job..
In your case, because you create a context instance without attach to any baseContext, so when access to common resource, you got a NPE.
I guess that you are trying to move to a new Fragment or Actvity? Then read these link start activity switch fragment