This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
please I am new to android development.I am working on the flag quiz app on ditel's android 6 for programmers. Although I followed the source code meticulously, I don't seem to be able to run the app successfully, as it crashes almost immediately after coming up. This is the exception I am getting. I would appreciate any help that will solve this problem.
FATAL EXCEPTION: main
Process: com.example.israel.flagquiz, PID: 4644
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.israel.flagquiz/com.example.israel.flagquiz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.israel.flagquiz.MainActivityFragment.updateGuessRows(android.content.SharedPreferences)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.israel.flagquiz.MainActivityFragment.updateGuessRows(android.content.SharedPreferences)' on a null object reference
at com.example.israel.flagquiz.MainActivity.onStart(MainActivity.java:62)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1244)
at android.app.Activity.performStart(Activity.java:6140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2601)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
pertinent code in MainActivity
#Override
protected void onStart(){
super.onStart();
if (preferencesChanged){
MainActivityFragment quizFragment = (MainActivityFragment)
getSupportFragmentManager().findFragmentById(R.id.quizFragment);
quizFragment.updateGuessRows(
PreferenceManager.getDefaultSharedPreferences(this));
quizFragment.updateRegions(
PreferenceManager.getDefaultSharedPreferences(this));
quizFragment.resetQuiz();
preferencesChanged = false;
}
pertinent code in Main Activity Fragment
public void updateGuessRows(SharedPreferences sharedPreferences){
String choices = new String();
choices = sharedPreferences.getString(MainActivity.CHOICES, null);
guessRows = Integer.parseInt(choices) / 2;
for (LinearLayout layout: guessLinearLayouts)
layout.setVisibility(View.GONE);
for (int row = 0; row < guessRows; row++)
guessLinearLayouts[row].setVisibility(View.VISIBLE);
}
sharedPreferences is null at this line
choices = sharedPreferences.getString(MainActivity.CHOICES, null);
initialize sharedPreferences in on Start
Add the below line to initialize your shared preferences
If using in an Activity
sharedPreferences = getSharedPreferences("MainActivity", Context.MODE_PRIVATE);
If using in a Fragment
sharedPreferences = getActivity().getSharedPreferences("MainActivity", Context.MODE_PRIVATE);
Once it is initialized, you can read data from shared preferences file.
Related
Hi this is my first question here, I'm working on a google nearby place app, I'm getting a crash every time I click on the marker place to get the details, and yes I have enabled billing in google developer API
Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.androidnearbyplaces.Model.Result.getFormatted_address()' on a null object reference
at com.example.androidnearbyplaces.ViewPlace$2.onResponse(ViewPlace.java:88)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:81)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$3wC8FyV4pyjrzrYL5U0mlYiviZw.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
This is the ViewPlace.java:88
mService.getDetailPlace(getPlaceDetailUrl(Common.currentResult.getPlace_id())).enqueue(new Callback<PlaceDetail>() {
#Override
public void onResponse(Call<PlaceDetail> call, Response<PlaceDetail> response) {
mPlace = response.body();
place_address.setText(mPlace.getResult().getFormatted_address());
place_name.setText(mPlace.getResult().getName());
}
#Override
public void onFailure(Call<PlaceDetail> call, Throwable t) {
}
});
Quick explanation:
mPlace.getResult() is returning null. NullPointerException is being thrown because you cannot do null.getFormattedAddress(). You cannot call any method on null in Java.
Why does it return null? I cannot tell for sure without seeing more of the code.
Please read more about NullPointerException, maybe in here.
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
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 trying to edit a custom arraylist from another Activity the application force closed.
Arraylist in MainActivity:
ArrayList<Contacts> contacts = new ArrayList<Contacts>();
Another Activity:
MainActivity main = new MainActivity();
main.contacts.get(position).contactname=x;
main.contacts.get(position).contactnumber=x;
How can I edit an arraylist from another activity?
Logcat:
09-08 22:53:40.415 1760-1760/com.example.amir_p.contacts E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.amir_p.contacts, PID: 1760
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { (has extras) }} to activity {com.example.amir_p.contacts/com.example.amir_p.contacts.ContactInfo}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at android.app.ActivityThread.deliverResults(ActivityThread.java:3577)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3620)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.amir_p.contacts.ContactInfo.onActivityResult(ContactInfo.java:53)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3573)
Two issues:
1
You can't instantiate an activity:
new MainActivity();
Activities must be launched from an Intent like so:
thisActivity.startActivity( new Intent( NextActivity.class ) );
2
If you want two activities to share a list, then you must instantiate that list in a greater scope, like the Application scope by creating a custom application class or creating a singleton.
Singleton:
public final class MySingleton {
private static final MySingleton SELF = new MySingleton();
private List<Contacts> contacts = new ArrayList<Contacts>();
private boolean didContacts
private MySingleton() {
// Don't want anyone else constructing the singleton.
}
public static MySingleton getInstance() {
return SELF;
}
public List<Contacts> getContacts() {
return contacts;
}
}
Now in any activity you like you may get the list
MySingleton.getInstance().getContacts()
Just be careful of concurrent modification.
Amendment due to a request in comments
It was stated in the comments that you want to change one activity from another. You must realize only one activity is active at a time and so you SHOULD NOT do that, regardless of whether or not you could hack it. I would normally recommend a listener but a listener wont work in this case since only one Activity Another way to do this would be to have some in-memory state that lives outside the activity (maybe the singleton) that the activities can respond to when they regain focus.
Pseudo code
ActivityB {
onClick() {
MySingleton.getInstance().getContacts().add( theContact );
}
}
ActivityA {
onResume() {
// consider contacts may have changed and redraw
listViewAdapter.clear();
listViewAdapter.addAll( MySingleton.getInstance().getContacts() );
}
}