I am working on my first app (so please forgive me if I've made a silly mistake, I am relatively new to coding). I created a settings activity for my app, but the moment I click on the settings button from the action bar, my app crashes. I tried debugging the app, turns out the moment I remove the lines where I keep the switches on setchecked, it works fine, but then if I remove the app from memory and open it again, the setting isnt saved, the switches aren't on. Please help.
package com.example.taskmasterv3;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Switch;
public class SettingsActivity extends AppCompatActivity {
public static final String SETTINGS_PREFERENCES = "com.example.taskmasterv3.SettingsPreferences";
Switch switchReminder, switchNotifications;
boolean reminders;
boolean notifications;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
SharedPreferences prefs = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE);
reminders = prefs.getBoolean("reminders", false);
notifications = prefs.getBoolean("notifications", false);
switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications);
switchReminder = findViewById(R.id.switchReminder);
switchNotifications = findViewById(R.id.switchNotifications);
if (switchReminder.isChecked()) {
reminders = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("reminders", reminders);
editor.commit();
}
if (switchNotifications.isChecked()) {
notifications = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("notifications", notifications);
editor.commit();
}
}
}
You're not using findViewById to retrieve your switches in onCreate before you're using them, so they're null:
switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications); <-- wrong order
switchReminder = findViewById(R.id.switchReminder); <-- too late, already tried to use it above
switchNotifications = findViewById(R.id.switchNotifications);
it should be:
switchReminder = findViewById(R.id.switchReminder);
switchNotifications = findViewById(R.id.switchNotifications);
switchReminder.setChecked(reminders);
switchNotifications.setChecked(notifications);
Related
package comviewappisome.google.sites.watchandearn;
public class SharedPreferences {
public static final String PREFS_NAME = "MyLoginPrefsFile";
}
package comviewappisome.google.sites.watchandearn;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import static comviewappisome.google.sites.watchandearn.SharedPreferences.PREFS_NAME;
public class login extends AppCompatActivity {
LinearLayout guestlogin = (LinearLayout )findViewById(R.id.guest);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
guestlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences settings = getSharedPreferences(comviewappisome.google.sites.watchandearn.SharedPreferences.PREFS_NAME, 0); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
//Set "hasLoggedIn" to true
editor.putBoolean("hasLoggedIn", true);
// Commit the edits!
editor.commit();
Intent i = new Intent(login.this, ChoiceSelection.class);
startActivity(i);
}
});
}
}
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
SharedPreferences settings = getSharedPreferences(comviewappisome.google.sites.watchandearn.SharedPreferences.PREFS_NAME, 0);
//Get "hasLoggedIn" value. If the value doesn't exist yet false is returned
boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);
if(hasLoggedIn)
{
Intent i = new Intent(SplashScreen.this, login.class);
this.startActivity(i);
this.finish();
}
else
{
Intent n = new Intent(SplashScreen.this, ChoiceSelection.class);
this.startActivity(n);
this.finish();
}
}
}
This, I code in javafile and then this error show me while debug.I delete this files also and set file to previously, but I did not get any solution. My build.gradle and main.xml is also right and there is error showing while gradle sync only in debuging.I try Restart and Invalides Caches
I think this problem is caused by other classes. If you are using a web service, the json format returned from there is the wrong format.
Your client expects an array (or JSON array) but it gets an string (starts with '"') . check your string and find out the difference between. maybe it needs to remove quotation marks from start and end. but to be honest, you must LOG them to get a proper solution.
I fixed the problem by cleaning the build!
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
In my program I have around 20 check boxes however when I check them and close the program then go back on the check boxes they are always unchecked how can I make the check box remember to stay checked.
In your onPause function, write the states to a file or to a SharedPreference. In your onResume, read that file/Preference in and set the checkboxes. You may want to look at PreferenceActivity to do this for you.
You can use SharedPreferences to do this.
So first, when your application goes to onPause, you'll want to store the state of each checkbox in SharedPreferences:
SharedPreferences prefs = this.getSharedPreferences("com.example.myapp", Context.MODE_PRIVATE);
prefs.putBoolean("checkbox1", checkbox1.isChecked()).commit();
// do this for all 20
Then you can check the checkboxes onResume and onCreate:
checkbox1.setChecked(prefs.getBoolean("checkbox1", false));
You should look into using Shared Preferences .
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Writing to Shared Preferences :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Reading from Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Also here is a very simple tutorial on implementing them.
Requested Example Code :
Main Activity Class :
package com.zeus.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.CheckBox;
public class MainActivity extends Activity {
CheckBox chkBox1, chkBox2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chkBox1 = (CheckBox) findViewById(R.id.checkBox1);
chkBox2 = (CheckBox) findViewById(R.id.checkBox2);
SharedPreferences getPrefs =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean value = getPrefs.getBoolean("checkbox_preference", true);
chkBox1.setSelected(value); // Setting the value reflected from the preference
chkBox2.setSelected(!value); // Setting the value opposite of the preference(Just an example)
}
}
Preference Activity Class :
package com.zeus.example;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity{
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
Settings XML :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="checkbox_preference"
android:defaultValue="false"
android:title="CheckBox1"
/>
</PreferenceScreen>
Although this method is easy, it's deprecated and is recommended to use Preference Fragments instead
Use SharedPreferences. The simplest way to store small values forever.
Since you have multiple check boxes use SharedPreferences.Editor putStringSet (String key, Set<String> values)
You can use SimpleSharedPreferences in which putStringSet is backported to API-1.
Usage: No Edit, No Commit.
SimpleSharedPreferences mPreferences = new SimpleSharedPreferences(getApplicationContext()); //Init.
mPreferences.putStringSet("STRING_SET_KEY", mStringSet); //Single Line
mPreferences.getStringSet("STRING_SET_KEY", null); // Get String set.
mPreferences.putBoolean("INTEGER_BOOL", true); //Just an example.
Note : I am the author of SimpleSharePreferences.
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
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).