I'm working on an app and would like to save the state of obe of my checkbox options, but when I try using the SharedPreferences class (first time using it) I get a nullpointer exception. I have been troubleshooting for a couple hours and cant find a solution. Could anyone look at this and tell me what's wrong? The full code is alot longer but this is the park giving me the null pointer exception. I know for a fact it has to do with SharedPreferences.
package us.mattmccoy.meanfind;
//import java.util.Arrays;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
//saved data stuff needed
SharedPreferences preferences = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
Editor edit = preferences.edit();
//private data using saved data
String autoclearKEY = "us.mattmccoy.meanfind.AUTOCLEAR";
boolean autoclear = preferences.getBoolean(autoclearKEY, false);
//normal private data
final Context con1 = this;
int dividend;String dataFixed;boolean tb;
private CheckBox myCBox, acBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerBoxes();
if(autoclear == true){
acBox.setChecked(true);
}else{
acBox.setChecked(false);
}
}
//check box listeners
public void addListenerBoxes(){
//instantiate boxes
acBox = (CheckBox) findViewById(R.id.chex2);
acBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//is acBox checked?
if (((CheckBox) v).isChecked()) {
edit.putBoolean(autoclearKEY, true).commit();
}else{
edit.putBoolean(autoclearKEY, false).commit();
}
}
});
myCBox = (CheckBox) findViewById(R.id.chex);
}
error message:
http://pastebin.com/5P2Mfwik
Change this line
SharedPreferences preferences = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
to
SharedPreferences preferences; = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
and put
preferences = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
in onCreate()
You are trying to use Context before establishing it with onCreate() so you are getting NPE on context. You will also want to move these lines
Editor edit = preferences.edit();
boolean autoclear = preferences.getBoolean(autoclearKEY, false);
into onCreate() after you initialize preferences or you will get another NPE since preferences will be null until you initialize it. So it should be something like
public class MainActivity extends Activity {
//saved data stuff needed
SharedPreferences preferences; //declare them
Editor edit;
//private data using saved data
String autoclearKEY = "us.mattmccoy.meanfind.AUTOCLEAR";
boolean autoclear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences; = this.getSharedPreferences("us.mattmccoy.meanfind", Context.MODE_PRIVATE);
Editor edit = preferences.edit(); //initialize them
boolean autoclear = preferences.getBoolean(autoclearKEY, false);
addListenerBoxes();
if(autoclear == true){
acBox.setChecked(true);
}else{
acBox.setChecked(false);
}
If this doesn't solve your problem then please post full logcat
Related
I'm trying to get some data from Word Readable Shared Preferences of another application.
I'm sure that other application Shared Preferences is World Readable and name is present.
But I'm retrieving empty string.
Here is my code:
package com.example.sharedpref;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.content.SharedPreferences;
public class MainActivity extends AppCompatActivity {
private TextView appContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContent = (TextView) findViewById(R.id.test1);
appContent.setText("Test Application\n");
appContent.setText(getName(this));
}
protected String getName(Context context){
Context packageContext = null;
try {
packageContext = context.createPackageContext("com.application", CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = packageContext.getSharedPreferences("name_conf", 0);
String name = sharedPreferences.getString("name", "");
return name; //HERE IS WHERE I PUT BREAKPOINT
}
catch (PackageManager.NameNotFoundException e) {
return null;
}
}
}
Here is some debug I retrieve from debug mode:
and piece of code from the app that I'm trying to access shared preferences:
/* access modifiers changed from: protected */
#SuppressLint({"WorldReadableFiles"})
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_welcome);
Editor edit = getApplicationContext().getSharedPreferences("name_conf", 0).edit();
edit.putBoolean("FIRSTRUN", false);
edit.putString("name", "Eddie");
edit.commit();
new DBHelper(this).getReadableDatabase();
PS. I Cant edit code of second app im trying access to!
Something im missing?
You can not edit it from another apps,
if you want, you can use FileWriter to create a txt file and use it in other apps
Hi I'm currently trying to save a simple integer value from an EditText to sharedPreferences so that I can access it within any activity. I've tried following the google tutorials but I was unable to make it work. I ended up getting the error message "Cannot resolve method 'getPreferences' ". I realize that there have been other threads about sharedPreferences but I cannot seem to make sense of them.
Also, if you can help me find a better way than my catch statement to avoid the NumberFormatException, please let me know. Thanks again!Any help is much appreciated!
Java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static com.managergmail.time.finite.finitemanager02.R.id.textViewTest;
public class ExamPrepHome extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exam_prep_home);
Button buttonSaveNumberOfExams = (Button) findViewById(R.id.buttonSaveNumberOfExams);
try{
final EditText numberOfExamsInput = (EditText) findViewById(R.id.numberOfExamsInput);
final int numberOfExamsValue = Integer.valueOf(numberOfExamsInput.getText().toString());
buttonSaveNumberOfExams.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_number_of_exams), numberOfExamsValue);
editor.commit();
}
});
}catch(NumberFormatException ex){
System.out.println("Value at TextView is not a valid integer");
}
}
}
Instead of
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
use SharedPreferences sharedPref = ExamPrepHome.this.getPreferences(Context.MODE_PRIVATE);
Reason for this is because inside the anonymous class, 'this' represents that inner class and not the Activity object. And you have to use number format exception to check to avoid crashes when you retrieve the object.
I have code in which it has an editText box and a button. I want to save the text entered in the textbox and recall it the next time the app is opened.
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText txtLink;
Button btnOpenLink;
String defaultLink;
String secondLink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
defaultLink = "http://";
secondLink = ".whatver.com";
txtLink = (EditText) findViewById(R.id.editText);
btnOpenLink = (Button) findViewById(R.id.button);
btnOpenLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String server = txtLink.getText().toString();
if(!TextUtils.isEmpty(server)){
Intent intent=new Intent(MainActivity.this,webactivity.class);
intent.setData(Uri.parse(defaultLink+server+secondLink));
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Please enter your server name.", Toast.LENGTH_LONG).show();
}
}
});
}
}
How can this be accomplished? I have tried numerous things that I have found through google but none have seemed to work right, I know it is something that I am doing most likely, I just can not make it work right.
Use the preferences....
Example
SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("myTextViewValue", prefVal); //
editor.commit();
and somewhen latter when the app starts again read it back:
Example:
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
String storedPreference = preferences.getStr("myTextViewValue", null);
so validate what you store and check if the preference you get is null, that means nothing was stored before...
My probablem is I have all the code and there is no errors on it (accrording to eclipse) but when I try to open up "page1" on my app it freezes then crashes, if I get ride of all of the addPoints information the page runs fine, can you help me find out what is causing the crash? Thanks!
heres my code
package com.canadais.civics;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class page1 extends Activity implements OnClickListener
{
TextView Q1A1;
TextView Q1A2;
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
public int testScore = (settings.getInt("YourScore", 0));
Intent page2 = new Intent (this, Page2.class);
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Q1A1 = (TextView) findViewById(R.id.Q1A1);
Q1A2 = (TextView) findViewById(R.id.Q1A2);
Q1A1.setOnClickListener(this);
Q1A2.setOnClickListener(this);
//test = (TextView) findViewById(R.id.test);
//test.setText(settings.getInt("YourScore", 0));
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
addPoints(10);
//Intent page2 = new Intent (this, Page2.class);
startActivity(page2);
break;
case R.id.Q1A2:
addPoints(5);
//Intent page22 = new Intent (this, Page2.class);
startActivity(page2);
break;
}
}
public void addPoints(int points)
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + points));
editor.commit();
}
}
There are several possible reasons if you encounter problems after executing startActivity(). I can think of two right now:
Missing Activity declaration in AndroidManifest.xml;
Incorrect codes in the Activity(Page2.java in your case) to be started.
To ensure which error you have encountered, I suggest you should learn to post error message appeared in the LogCat which is bundled in Android SDK but not the one pop-up on the phone screen, otherwise, no one could accurately figure out the problem(s).
Ok, thanks to below dude biggest issue is fixed. But whatever I print out, none is printed and I cannot print out the message what is typed in class 2 (nimekysija) as well :(. I really need that it stores name and in future it will write down name every time! Thanks for your help!
Problem must be in 2nd class tho. When I update editor.putString("nimi2", nimiS); nimiS into "plapla", then plapla actually shows up :/. So I have really no idea, what is problem!
(updated below classes too to the newest)
Class 1:
package viimane.voimalus;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class MainStuff extends Activity {
TextView tere;
String nimi;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
tere = (TextView) findViewById(R.id.tvTere);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean nimiOlemas = preferences.getBoolean("nimionolemas", false);
if (nimiOlemas == false){
startActivity(new Intent("viimane.voimalus.NIMEKYSIJA"));
finish();
}
if (nimiOlemas == true){
nimi = preferences.getString("nimi2", "");
System.out.print("töötab!");
tere.setText("Tere " + nimi);
}
System.out.print("töötab2!");
}
}
CLASS 2
package viimane.voimalus;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class nimekysija extends Activity {
EditText nimi;
SharedPreferences preferences;
String nimiS;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nimekysija);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
nimi = (EditText) findViewById(R.id.etNimekysija);
nimiS = nimi.getText().toString();
Button kysOk = (Button) findViewById(R.id.bNimekysija);
kysOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = preferences.edit();
editor.putString("nimi2", nimiS); // nime kirjutamine
editor.putBoolean("nimionolemas", true); // nimi on kirjutatud!
editor.commit();
startActivity(new Intent("viimane.voimalus.MAINSTUFF"));
finish();
}
});
}
}
Ok I'm guessing you may be new to Java, forgive me if I'm incorrect. You never READ from nimiOlemas.
boolean nimiOlemas = preferences.getBoolean("nimionolemas", false);
nimiOlemas = false;
startActivity(new Intent("viimane.voimalus.NIMEKYSIJA"));
finish();
nimiOlemas = true;
I think what you are trying to do is initialize nimiOlemas and then, if it is false, start an activity, call finish, then set nimiOlemas to true, but this is not what you are doing. Is this what you want?
boolean nimiOlemas = preferences.getBoolean("nimionolemas", false);
if (nimiOlemas == false)
{
startActivity(new Intent("viimane.voimalus.NIMEKYSIJA"));
finish();
nimiOlemas = true;
}
= is an assignment, == is a boolean comparison. You say in your question that you check the value of your boolean, but you never do, you only assign to it.
Assuming that nimiOlemas is inherited from activity and not used in the activity class, or other supper class, then yes it is not used in nimekysija (Class 2). It IS used in class 1. But this should just be a warning... You will get this warning for every class that extends activity and doesn't use nimiOlemas.