Im trying to use edittexts on my second activity to change strings on my first/main activity. So to do that, one must use SharedPreferences.
At the top of my second activity, I had declared them and an editor. It causes a nullpointexception error and crashes the code. I'm not sure where to initalize this as I want the sharedPreferences to be looked at in the main/first activity.
SharedPreferences settings = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = settings.edit();
Also, is this proper code to put in the sharedprefs dictionary?
if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
{
editor.putString("intro", introstring);
}
At the top of my second activity
You mean as fields - yes this will cause a NPE for reasons explained in Why getApplicationContext() in constructor of Activity throws null pointer exception?
So as suggested in the comments you need to
class YourSecondActivity extends Activity {
SharedPreferences sp;
Editor e;
protected void onCreate() {
sp = PreferenceManager.getDefaultSharedPreferences(this); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
}
meth() {
//...
if(!introstring.isEmpty()) { // save the fields if NOT empty
e.putString("intro", introstring);
e.commit(); // you forgot to commit
}
}
}
My way of handling SharedPrefrences is to create a class that will extend Application class and put SharedPrefrences there so that will be accessible everywhere in the app.
class MyApp extends Application{
SharedPreferences sharedPreferences;
public void onCreate() {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
public static getSharedPrefrences(){
return sharedPrefrences;
}
}
you have to put declare the name tag of the application in the activity tag
<application
android:allowBackup="true"
android:name=".fundamentals.UploadApp"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
....
....
</application>
Then, you can access it from any Activity that you want.
class SomeActivity extends Activity{
onCreate(){
SharedPrefences prefs = MyApp.getSharedPrefrences();
}
}
also, you need to commit the change after you have put something in the SharedPrefrences
if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
{
editor.putString("intro", introstring).commit();
}
Related
public class ustawienia extends MainActivity {
EditText kryptonim;
public String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ustawienia);
kryptonim = (EditText) findViewById(R.id.edit_kryptonim);
test = kryptonim.getText().toString();
}
public String call_back(){
return test;
}
}
When call call_back() from another class I've got error: Unable to start activity ComponentInfo. What's wrong with that?
When you close an activity all data from it is lost, so unless both activities are runing at the same time you can't retrieve data. You could use shared prefrences instead.
// IN ORDER TO WRITE TO A FILE
SharedPreferences.Editor prefs = getSharedPreferences("PrefsName", MODE_PRIVATE).edit();
prefs.putString("test", kryptonim.getText().toString());
prefs.apply(); // use prefs.commit(); if this doesn't work
In order to read data
SharedPreferences prefsR = getSharedPreferences("PrefsName", MODE_PRIVATE); // you could also write 0 instead MODE_PRIVATE
String restoredText = prefsR.getString("test", null);
Ofcourse you need to import SharedPrefs , and put this in oncreate or wherever you want... let me now if it works :)
i don´t know where i have to setup the initial value of this variable:
mySharedPreferences.putStringValue("hello", "400");
And it don´t be reset if it is changed every time i open the app.
Thank you!!
The best way to do that is to "set" the default value on get method instead of set it on the first start of your app.
mySharedPreferences.getString("hello", "400");
On this way android checks if there was an value set. If not, it will fallback to the default "400".
Take a look at the documentation:
https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String, java.lang.String)
And in application tag
<application
android:name=".YourApplication"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
In Application's onCreate Method. It is best place. It will be executed when your app is created.
public class YourApplication extends Application {
public static Boolean sAppOpened = false;
#Override
public void onCreate() {
super.onCreate();
//Write your code here
sAppOpened = true;
....
}
...
}
Declare your SHARED PREFERENCE file name class-wide like this -
public static final String SHARED_PREFERENCES = "SHARED_PREF";
You can use this in your OnCreate method.
SharedPreferences sharedpreferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
I'm building an android project that contains SharedPreferences.
My SharedPreferences works fine and I tested it in mutiple activity. but in a class that I defined for global variables, defining that SharedPreferences will cause force close (eclipse didn't show any error in codes).
public class Globals extends Application {
final SharedPreferences s = getSharedPreferences("Prefs", MODE_PRIVATE);
}
What is the problem ?
You should pass the Context and use
SharedPreferences prefs = Context.getSharedPreferences(
"Prefs", Context.MODE_PRIVATE);
Create a constructor and pass a Context variable as a parameter. Any activity that want to use this preference then you have to pass the activity. Here's the code given below:
public class Globals extends Application {
private Context context;
public Globals (Context context) {
this.context = context;
}
SharedPreferences myPref = context.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
}
You can't run getSharedPreferences() in the actual class. Everything you do must be in the Application's onCreate method. If you try to run this in the class, it will fail since it has not been initialized yet. Think of it almost as an activity, since both the activity and the application have a lifecycle.
Try the following:
public class Globals extends Application {
#Override
public void onCreate() {
super.onCreate();
final SharedPreferences s = getSharedPreferences("Prefs", MODE_PRIVATE);
}
}
This question already has answers here:
Run code only once after an application is installed on Android device
(5 answers)
Closed 7 years ago.
I want to run a piece of code only once in my application and is when i run it for the first time (newly installed app). How could i do this, can anyone explain giving a piece of code.
Actually, in my android project i want to create database and insert some values on the first run only. After that, that particular piece of code should not run again. How can i achieve this mechanism through SharedPreferences or Preferences.
Sample code will be more helpful.
Before all you can use SQLiteOpenHelper. It is preferred way to do things with database. This class have a onCreate(SQLiteDatabase) method, that called when first creating database. I think it suits you well.
If you want more flexibility and your first time logic is not tied only with database, you can use sample provided earlier. You just need to put it in startup spot.
There are 2 startup spots. If you have only single activity, you can put your code in onCreate method, so it will be like this:
public void onCreate(Bundle savedInstanceState) {
// don't forget to call super method.
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();
// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
Don't forget to put activity declaration in manifest, as well as it's intentfilters (action = MAIN, category = LAUNCHER).
If you have more than one activity and you don't want to duplicate your startup logic you can just put your initialization logic in Application instance, that is created before all activities (and other components, such as services, broadcast recievers, content providers).
Just create class like that:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();
// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
All you need for this to work, is put in application tag in AndroidManifest.xml attribute android:name=".App".
<!-- other xml stuff -->
<application ... android:name=".App">
<!-- yet another stuff like nextline -->
<activity ... />
</application>
You could try :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
SharedPreferences.Editor editor = wmbPreference.edit();
if (isFirstRun){
// Code to run once
editor.putBoolean("FIRSTRUN", false);
editor.apply();
}
Write this in your first activity on create. Then after the code will not execute again.
here's what I do in those situations :
wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
if (isFirstRun)
{
// Do your magic here
SharedPreferences.Editor editor = wmbPreference.edit();
editor.putBoolean("FIRSTRUN", false);
editor.commit();
}else{
//what you do everytime goes here
}
hope this helps
Wherever you need to run this code in your app:
Check if boolean firstTime is True in shared preferences
If not
Run the one time code
Save firstTime as true in shared preferences
Something like this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code here
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
I use some CheckBoxPreferences, but they are not indepentent. That means, wenn I change one CheckBoxPreference, others are fixed. I use the following code:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String key) {
SharedPreferences.Editor editor = sharedPrefs.edit();
if ((key.equals("A")) & (key.equals("B"))) {
editor.putBoolean("C", true);
editor.commit();
}
}
}
After this the CheckBoxPreference "C" has a new value, but I can't see it. How can I update the screen with the new values?
By using a subclass of PreferenceActivity you do not have to handle the updating of the preferences UI. You define the preferences in the resource file loaded by addPreferencesFromResource() and the Activity will be rendered accordingly. Changes will be persisted automatically and should be visible immediately. You do not have to register your preferences Activity as a SharedPreferences.OnSharedPreferenceChangeListener.
When onSharedPreferenceChanged() is called the new value is already saved to the preferences.
This notification is for other Activities than the subclasses of PreferenceActivity. To know how to access the saved preferences you need to look at the file in res/xml/settings.xml it should contain android:key attributes. The attribute values give you the key to the preference.
You can retrieve the value via the following:
PreferenceManager.getDefaultSharedPreferences(aContext).getString(key, "");