Cannot get .edit() and .apply() to update values - java

I am new to Android Studio and learning how to create SharedPreference variables. I'm stuck that,updating the value of the string in SharedPreference raises a NullPointerException when I execute below code. Any help will be much appreciated. Thanks in advance.
This is my SettingPage
#Override //Creating the setting page
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settingpage);
setMinsBar = findViewById(R.id.numMinsBar);
setTimeEnterButton = findViewById(R.id.setTimeButton);
musicYesSwitch = findViewById(R.id.musicSwitch);
soundYesSwitch = findViewById(R.id.soundSwitch);
minsLeftTV = findViewById(R.id.minsLeftTV);
timerEndsTV = findViewById(R.id.timerEndsTV);
varAcrossApp = this.getSharedPreferences(SP, Context.MODE_PRIVATE);
//Setting on click listener for the enter button for the time set
setTimeEnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timeInInt = Integer.parseInt(setMinsBar.getText().toString());
saveData();
}
});
}
public void saveData(){ //Declaring method saveData
varEditor = varAcrossApp.edit();
varEditor.putInt(timeInStringSP, timeInInt);
varEditor.putBoolean(musicYesSP, musicYesSwitch.isChecked());
varEditor.putBoolean(soundYesSP, soundYesSwitch.isChecked());
varEditor.apply();
Toast.makeText(getApplicationContext(), "Duration set", Toast.LENGTH_SHORT).show();
}
public void loadData(){ //Declaring method loadData
finalTimeInMins = varAcrossApp.getInt(timeInStringSP, 0);
musicYes = varAcrossApp.getBoolean(musicYesSP, false);
soundYes = varAcrossApp.getBoolean(soundYesSP, false);
}
public void updateView() {
minsLeftTV.setText(finalTimeInMins);
if (musicYes = true) {
timerEndsTV.setText("-Turn off music");
} else if (soundYes = true) {
timerEndsTV.setText("-Change sound profile to 'Sound'");
} else if (musicYes && soundYes) {
timerEndsTV.setText("-Turn off music /n-Change sound profile to 'Sound'");
} else {
timerEndsTV.setText("-Do nothing");
}
}
This is MainActivity
#Override //Creating the app here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
startButton = findViewById(R.id.startButton);
SettingPage settingPage = new SettingPage();
settingPage.loadData();
settingPage.updateView();
}
Error Code and Stack trace given below:
Process: com.example.sleep, PID: 6935
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sleep/com.example.sleep.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
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:934)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference
at com.example.sleep.SettingPage.loadData(SettingPage.java:77)
at com.example.sleep.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:7783)
at android.app.Activity.performCreate(Activity.java:7772)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7319) 
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:934)

You should not call varAcrossApp.getInt before varAcrossApp = this.getSharedPreferences(SP, Context.MODE_PRIVATE);
This is how shared preferences should/can be used in android.
class SettingsSpDao { // shared preferences data access object
private static final String SP = "SP";
private static final String MUSIC_YES = "music_yes";
public static boolean isMusicYes(Context context) {
// you can initialize sp beforehand so you don't have to pass in context but I prefer it this way, so I don't have to initialize it before using it
SharedPreferences sp = context.getSharedPreferences(SP, Context.MODE_PRIVATE);
return sp.getBoolean(MUSIC_YES , false);
}
// add your methods here
}
// call it anywhere as long as you can pass a context, such as Activity.
musicYes = SettingsSpDao.isMusicYes(this); // in your case `this` since it's in an Activity

Related

I get java.lang.NullPointerException: Attempt to invoke virtual method when I save details in my app [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I want to enter details from EnterDetails class and view saved details in MainActivity.
public class MainActivity extends AppCompatActivity {
EditText nameBox ;
EditText sclBox;
Spinner genderMenu;
EditText ageBox;
SharedPreferences sharedPref;
TextView label ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameBox = findViewById(R.id.editText);
sclBox = findViewById(R.id.editText3);
ageBox = findViewById(R.id.editText2);
genderMenu = findViewById(R.id.spinner);
sharedPref = getSharedPreferences("mypref",Context.MODE_PRIVATE);
label = findViewById(R.id.textView);
if(isDetailsEmpty(0)){
label.setText("Enter new Details");
}else{
setDetails();
}
}
public boolean isDetailsEmpty(int i){
if(i ==0) {
if (sharedPref.getString("txtName", "").isEmpty() || sharedPref.getString("txtAge", "").isEmpty() || sharedPref.getString("txtScl", "").isEmpty()) {
return true;
} else {
return false;
}
}{
if(nameBox.getText().toString().isEmpty() || ageBox.getText().toString().isEmpty() || sclBox.getText().toString().isEmpty()){
return true;
}else{
return false;
}
}
}
public void setDetails(){
label.setText("Name : " +sharedPref.getString("txtName","Default")+"\n"+
"Age : " +sharedPref.getString("txtAge","Default")+"\n"+
"Gender : " +sharedPref.getString("optGender","Default")+"\n"+
"School : " +sharedPref.getString("txtScl","Default")+"\n");
}
public void onClickLoadIntent(View v){
Intent enterDet = new Intent(this, EnterDetails.class);
startActivity(enterDet);
}
}
`public class EnterDetails extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_details);
}
public void onClickSave(View v){
if(isDetailsEmpty(1)) {
Toast.makeText(EnterDetails.this,"Empty Details!", Toast.LENGTH_SHORT).show();
}else{
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("txtName", nameBox.getText().toString());
editor.putString("txtAge", ageBox.getText().toString());
editor.putString("optGender", genderMenu.getSelectedItem().toString());
editor.putString("txtScl", sclBox.getText().toString());
editor.commit();
Toast.makeText(EnterDetails.this,"Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this,MainActivity.class));
}
}
}
`
I want to enter details from EnterDetails class and view saved details in MainActivity. But I get the folloing error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.userdetails, PID: 31945
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5646) 
at android.view.View$PerformClick.run(View.java:22473) 
at android.os.Handler.handleCallback(Handler.java:761) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:156) 
at android.app.ActivityThread.main(ActivityThread.java:6517) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.userdetails.MainActivity.isDetailsEmpty(MainActivity.java:64)
at com.example.userdetails.EnterDetails.onClickSave(EnterDetails.java:20)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:5646) 
at android.view.View$PerformClick.run(View.java:22473) 
at android.os.Handler.handleCallback(Handler.java:761) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:156) 
at android.app.ActivityThread.main(ActivityThread.java:6517) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832) 
How to fix this? I have already extended EnterDetails to MainActivity.
Similar Question : What is a NullPointerException, and how do I fix it?
What you are doing is wrong. EnterDetails has its own layout called R.layout. enter_details, so when you set setContentView(R.layout.enter_details);, it will override the whole content so all views and layouts in MainActivity is no longer accessible. What you need to do is implement EnterDetails normally and use Intent to send data between activities.
public class EnterDetails extends AppCompatActivity {
private boolean isDetailsEmpty = false;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.enter_details);
isDetailsEmpty = getIntent().getBooleanExtra("test1", false)
}
public void onClickSave(View v){
if(isDetailsEmpty) {
...
}
}
And pass data from your MainActivity
public void onClickLoadIntent(View v){
Intent enterDet = new Intent(this, EnterDetails.class);
enterDet.putExtra("test1", isDetailsEmpty(1))
startActivity(enterDet);
}
Finally, please do more research on how Activity works https://medium.com/#peterekeneeze/passing-data-between-activities-2d0ef122f19d

Arithmetic Android app crashes, no errors in the code [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm making an Android app, it should ask for arithmetic equations and check the answer. There should be different difficulty levels as well. My app crashes when choosing the difficulty level from AlertDialog. I have no errors in Android Studio.
Here is the code for choosing level:
public void onClick(View view) {
if(view.getId()==R.id.play_btn){
//play button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a level")
.setSingleChoiceItems(levelNames, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//start gameplay
startPlay(which);
}
});
AlertDialog ad = builder.create();
ad.show();
}
private void startPlay(int chosenLevel){
//start gameplay
Intent playIntent = new Intent(this, PlayGame.class);
playIntent.putExtra("level", chosenLevel);
this.startActivity(playIntent);
}
Can someone help me understand why my app crashes?
Here is the log:
9758-9758/org.example.braintraining E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.example.braintraining, PID: 9758
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.braintraining/org.example.braintraining.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) 
at android.app.ActivityThread.access$900(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5942) 
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:1388) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183) 
Here is the code for onCreate method of PlayGame class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playgame);
gamePrefs = getSharedPreferences(GAME_PREFS, 0);
//text and image views
question = (TextView)findViewById(R.id.question);
answerTxt = (TextView)findViewById(R.id.answer);
response = (ImageView)findViewById(R.id.response);
scoreTxt = (TextView)findViewById(R.id.score);
//hide tick cross initially
response.setVisibility(View.INVISIBLE);
//number, enter and clear buttons
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
btn0 = (Button)findViewById(R.id.btn0);
enterBtn = (Button)findViewById(R.id.enter);
clearBtn = (Button)findViewById(R.id.clear);
//listen for clicks
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
enterBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
//get passed level number
if(savedInstanceState!=null){
//restore state
}
else{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) level = passedLevel;
level=savedInstanceState.getInt("level");
int exScore = savedInstanceState.getInt("score");
scoreTxt.setText("Score: "+exScore);
}
}
//initialize random
random = new Random();
//play
chooseQuestion();
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference at org.example.braintraining.PlayGame.onCreate(PlayGame.java:10‌​4)
Either the code might be failing in two scenarios:
You are starting new activity by passing the playIntent. Please check the code in PlayGame.java, in onCreate() you should be getting the string value (level) from Intent rather than from Bundle, something like
String chosenLevel;
Intent i = this.getIntent();
if(i != null){
chosenLevel = i.getStringExtra("level");
}
2.if you are rotating the screen, once you are in the play game activity where you are not saving the required value before the activity is destroyed and trying to retrieve it back once the activity is recreated .
Solution would be to use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putString("value", chosenLevel);
}
And restore the value from Bundle in onCreate() or you can use onRestoreInstanceState(), which is called after onStart(), whereas onCreate() is called before onStart().:
public void onCreate(Bundle bundle) {
if (bundle!= null){
chosenValue = bundle.getString("value");
}
}

How to display passed intent data in a TextView - NullPointerException error

I am making an app to display data from a database into a list view. When an item on the list view is clicked, it takes the user to a new activity where they can view more details about that item. I want to make the details page dynamic to display the details and have managed to show the title of the list view item in a toast.
Now, I am trying to display this by using setText() to show the title in a string but am getting the error:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kathe.parenttripapp, PID: 22849
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kathe.parenttripapp/com.example.kathe.parenttripapp.Details}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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) 
this is the class the error occurs at:
TextView titletext;
final List<Activitytable> activityTable = Activitytable.listAll(Activitytable.class);
String data = getIntent().getSerializableExtra("listPosition").toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
TextView titletext = (TextView) findViewById(R.id.titletext);
String data = getIntent().getSerializableExtra("listPosition").toString();
Toast.makeText(getBaseContext(),String.valueOf(data),Toast.LENGTH_LONG).show();
setData();
}
private void setData() {
Intent i = getIntent();
Bundle b = i.getExtras();
if (data != null) {
String j = (String) b.get("listPosition");
titletext.setText(j);
}
else{
titletext.setText("Hello");
}
}
This is the activity it has come from:
final ListView listView = (ListView) findViewById(R.id.viewAll_listview);
long count = Activitytable.count(Activitytable.class);
if(count>0) {
final List<Activitytable> activitytable = Activitytable.listAll(Activitytable.class);
final ViewAllListView madapter = new ViewAllListView(getApplicationContext(), activitytable);
listView.setAdapter(madapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?>parent, View v, int position, long id) {
String title = activitytable.get(position).Title.toString();
Activitytable AT = Activitytable.findById(Activitytable.class,activitytable.get(position).getId());
Intent i = new Intent(getApplicationContext(),Details.class);
i.putExtra("listPosition",title);
startActivity(i);
}
public Object getItem(int position) {return position;}
});
}
else
{
Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);
}
}
What I would like to do is to put the intent data into the TextView 'titletext' and then do an if statement saying if the passed intent data is equal to an activity title then display the following data but can't work out what is going wrong. I have tried using getStringExtra() instead of getSerializableExtra but no such luck. Works on toast but not on TextView.
If you don't have some good understanding of why you are doing so, try not to initialize your variables until you are in onCreate, also to prevent a NullPointerException, it is a good habit to use if (variable != null).
And you are storing an int, so use getIntExtra
TextView titletext;
List<Activitytable> activityTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
activityTable = Activitytable.listAll(Activitytable.class);
titletext = (TextView) findViewById(R.id.titletext);
Intent i = getIntent();
if (i != null) {
String data = i.getStingExtra("listPosition");
titletext.setText(String.valueOf(data));
}
}
In onCreate() and don't do it as a member variable.
Bundle intentBundle = getIntent().getExtras();
if (intentBundle != null) {
lastPosition = getInt( "lastPostion" );
}
The null pointer you are receiving is in the Details class on line 23
at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)

Getting null point exception when i declare latlong values globally

I have got latlong values using shared preferences and stored it as double values.
Declared latlong values globally.
Getting null point Exception.
Tried different ways of declaring values globally,but nothing seems working.
MainActivity.java
public class MapsActivityConnect extends FragmentActivity {
ImageView emerg;
SharedPreferences pref;
String vechile;
Double deslatituded, deslongituded, srclatituded, srclongituded;
private GoogleMap mMap = null;
private final LatLng end = new LatLng(deslatituded, deslongituded);
private final LatLng start = new LatLng(srclatituded, srclongituded);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_activity_connect);
pref = getSharedPreferences("gps", Context.MODE_PRIVATE);
Bundle extras = getIntent().getExtras();
if (extras != null) {
deslatituded = extras.getDouble("deslatitude");
deslongituded = extras.getDouble("deslongitude");
srclatituded = extras.getDouble("srclatitude");
srclongituded = extras.getDouble("srclongitude");
vechile = extras.getString("vechile");
if (!Utils.isConnected(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "Internet not available. Cross check your internet connectivity and try again", Toast.LENGTH_LONG).show();
return;
}
if (!Utils.isGPSTurnOn(getApplicationContext())) {
showGPSDialog();
return;
}
}
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
super.onResume();
if (Utils.isConnected(getApplicationContext())) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
final TextView txtDistance = (TextView) findViewById(R.id.txtSpeed);
new Routing(getParent(), mMap, txtDistance).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, start, end);
}
}
private void showGPSDialog() {
new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AppBaseTheme)) // Theme
.setTitle(R.string.gps_lable_gps) // setTitle
.setMessage(R.string.gps_lable_warning_message) // setMessage
.setInverseBackgroundForced(false).setCancelable(false) //
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int which) {
dialog.dismiss();
}
}).setIcon(android.R.drawable.ic_dialog_alert).show();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Utils.isGPSTurnOn(getApplicationContext())) {
onResume();
}
}
}
Logcat
9-29 13:40:56.383 32078- 32149/zybo.example.ramz.demo_location_tracking V/RenderScript﹕ Application requested CPU execution
09-29 13:40:56.393 32078- 32149/zybo.example.ramz.demo_location_tracking V/RenderScript﹕ 0xb7579cd8 Launching thread(s), CPUs 4
09-29 13:41:01.527 32078-32078/zybo.example.ramz.demo_location_tracking D/AndroidRuntime﹕ Shutting down VM
09-29 13:41:01.536 32078-32078/zybo.example.ramz.demo_location_tracking E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: zybo.example.ramz.demo_location_tracking, PID: 32078
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{zybo.example.ramz.demo_location_tracking/zybo.example.ramz.demo_location_tracking.MapsActivityConnect}: java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
at zybo.example.ramz.demo_location_tracking.MapsActivityConnect.<init>(MapsActivityConnect.java:62)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1089)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2240)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
at
android.app.ActivityThread.access$800(ActivityThread.java:155)
You need to initialize with values.
Double deslatituded, deslongituded, srclatituded, srclongituded;
You declare the doubles, but these are objects, not primitives. Therefore the default value is null. And the unboxing tries to get the primitive like
null.doubleValue()
Make them primitive or assign a default value like:
Double desLatituded = new Double(0);
I am not sure what is your error. But one of the scenario is
you declare class variables
private final LatLng end = new LatLng(deslatituded, deslongituded);
private final LatLng start = new LatLng(srclatituded, srclongituded);
Here deslatituded, deslongituded values must be null. Maybe this will the reason for the nullPoiner please check this.
You need to pass the values for this. Or just initialise the values like deslatituded=0 or something. This will save you from crash
Try this (and make sure your LatLng variables aren't final):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_activity_connect);
pref = getSharedPreferences("gps", Context.MODE_PRIVATE);
Bundle extras = getIntent().getExtras();
if (extras != null) {
deslatituded = extras.getDouble("deslatitude");
deslongituded = extras.getDouble("deslongitude");
srclatituded = extras.getDouble("srclatitude");
srclongituded = extras.getDouble("srclongitude");
// NEW CODE
end = new LatLng(deslatituded, deslongituded);
start = new LatLng(srclatituded, srclongituded);
// END NEW CODE
vechile = extras.getString("vechile");
if (!Utils.isConnected(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "Internet not available. Cross check your internet connectivity and try again", Toast.LENGTH_LONG).show();
return;
}
if (!Utils.isGPSTurnOn(getApplicationContext())) {
showGPSDialog();
return;
}
}
}
Please check if your extras has the key "deslatitude"
like:
if(getIntent().hasCategory("deslatitude"))
{
deslatituded = extras.getDouble("deslatitude");
}
Log.e(TAG, "deslatitude: " + deslatituded );
And if your log prints the valuew then check it for all (deslat,deslong,srclat,srclong)
Are there any values in
extras.getDouble("deslatitude");
extras.getDouble("deslongitude");
extras.getDouble("srclatitude");
extras.getDouble("srclongitude");
there is nothing in intent extras.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am trying to save player's name in shared preference and make it display in another activity by getting it again in shared preference but my app crash.
FATAL EXCEPTION: main
Process: plp.cs4b.thesis.drawitapp, PID: 1970
java.lang.RuntimeException: Unable to start activity ComponentInfo{plp.cs4b.thesis.drawitapp/plp.cs4b.thesis.drawitapp.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference
at plp.cs4b.thesis.drawitapp.PlayGame.onCreate(PlayGame.java:20)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
Codes:
Player.java
public class Player {
private Context context;
private SharedPreferences prefSettingsU;
private SharedPreferences.Editor prefEditorU;
private static final int PREFERENCE_MODE_PRIVATE = 0;
private static final String MY_UNIQUE_PREF_FILE = "DrawItApp";
public Player(Context context, String name) {
this.context = context;
saveName(name);
}
public void saveName(String n) {
prefSettingsU = context.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);
prefEditorU = prefSettingsU.edit();
prefEditorU.putString("keyName", n);
prefEditorU.commit();
}
public String getName(Context ctx) {
prefSettingsU = ctx.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);
String name = prefSettingsU.getString("keyName", "ANONYMOUS");
return name;
}
PlayGame.java
public class PlayGame extends Activity {
private TextView welcomePlayer;
private ListView createdGames;
private Player mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_game);
welcomePlayer = (TextView) findViewById (R.id.tvPlayerName);
welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");
createdGames = (ListView) findViewById (R.id.listCreatedGames);
// adapter etc
createdGames.setEmptyView(findViewById (R.id.tvNoGames));
}
PlayerName.java
public class PlayerName extends Activity {
private EditText playerName;
private Player mPlayer;
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_name);
context = this;
playerName = (EditText) findViewById (R.id.etName);
}
public void onC_Confirm(View btnclick) {
mPlayer = new Player(context, String.valueOf(playerName.getText()));
//mPlayer.saveName();
Intent intent = new Intent(PlayerName.this, PlayGame.class);
startActivity(intent);
}
public void onC_testShPref(View btnclick) {
Intent intent = new Intent(PlayerName.this, PlayGame.class);
startActivity(intent);
}
Your app is crashing at:
welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");
because mPlayer=null.
You forgot to initialize Player mPlayer in your PlayGame Activity.
mPlayer = new Player(context,"");

Categories

Resources