I am learning how to use shared preferences and I understand how to set it and get it with one class. However I want to be ale to use shared preferences across two classes. Let me explain.
So in the class below I am basically getting the total number of click counts for whenever the jokes, poems or funny stories button is clicked. This code is below (known as MainActivity):
public class MainActivity extends AppCompatActivity{
final Context context = this;
int clicksCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
storeClicks(clicksCount);
openContentPage("jokes");
}
});
poemsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
storeClicks(clicksCount);
openContentPage("poems");
}
});
funnyStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
storeClicks(clicksCount);
openContentPage("funnystories");
}
});
}
private void openContentPage(String v) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intentContentPage.putExtra("keyPage", v);
startActivity(intentContentPage);
}
public void storeClicks(int count)
{
SharedPreferences mSharedPreferences = getSharedPreferences("numberOfClicks", MODE_PRIVATE);
SharedPreferences.Editor meditor = mSharedPreferences.edit();
meditor.putInt("numberOfClicks", count);
meditor.apply();
}
public int getNumberOfClicks(){
SharedPreferences mSharedPreferences = getSharedPreferences("numberOfClicks", MODE_PRIVATE);
int clicksNumber = mSharedPreferences.getInt("numberOfClicks", clicksCount);
return clicksNumber;
}
}
However I have another class known as 'Content' and basically this contains a button known as 'Select Another'. I want this to be included with the click count as well.
So that's the goal basically, no matter what page I am on it should keep track of the number of clicks combined for buttons jokes, poems, funny stories and select another. How can this be implemented?
Below is the code for Content:
public class Content extends AppCompatActivity{
Button selectAnotherButton;
TextView contentText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
selectAnotherButton = findViewById(R.id.button_select_another);
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContent();
}
});
}
You can use Singleton pattern to implement global access to the SharedPreferences. Something like this:
public class SharedPreferencesManager {
private static final String APP_PREFS = "AppPrefsFile";
private static final String KEY_FOR_SOMETHING = "KEY_FOR_SOMETHING";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs =
context.getApplicationContext().getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public void setSomething(String something) {
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(KEY_FOR_SOMETHING, something);
editor.apply();
}
public String getSomeKey() {
String someValue = sharedPrefs.getString(KEY_FOR_SOMETHING, null);
return someValue;
}
}
You can have as much as you want methods for getting and setting various values to the SharedPreferences, and it will be accessible through the whole application, just do:
SharedPreferencesManager.getInstance(context).getSomeKey();
Shared Preference is just a common file that contains a set of Key Value Pairs.It would be accessible in any class from your App.
For your case , you can store it as a key value pair in one Class .
Then retrieve it using the same KeyName in another Class.It should retrieve the value you stored in the other class provided the flow is continous.
Please refer below existing stackoverflow answers for more info ::
Android Shared preferences example
Official Docs :
https://developer.android.com/training/data-storage/shared-preferences
Tutorial Example :
https://www.journaldev.com/9412/android-shared-preferences-example-tutorial
Related
I want to save the number value so that when close the app it continues to be saved and when open it the progress is maintained. I don't know why SharedPreferences don't work.
I have tried in many ways but either the app forces it to close or it just doesn't work
number = numero
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView contador;
int numero = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("valor", numero);
int data = mPrefs.getInt("valor", numero);
contador = findViewById(R.id.contador);
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor data = data.edit();
data.putInt("tag", numero).commit();
}
};
You should use the same sharedPreferences for retrieving the values.
also, get the values by the same key you saved them. below is an example you can follow.
SharedPreferences mPrefs = getSharedPreferences("valor",
Context.MODE_PRIVATE);
try{
int data = mPrefs.getInt("tag", numero);
}
catch(NullPointerException e){
e.printStackTrace()
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt("tag", numero).commit();
}
};
I tried many different ways but still not working.
Always get default values.
public class HookTest implements IXposedHookLoadPackage {
private XSharedPreferences sharedPreferences;
private final static String modulePackageName = HookTest.class.getPackage().getName();
public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
this.sharedPreferences = new XSharedPreferences(modulePackageName, "Values");
sharedPreferences.makeWorldReadable();
sharedPreferences.reload();
XposedBridge.log("Xposed_test value: " +sharedPreferences.getBoolean("isRunning", false));
}
}
i tried in MainActivity it's work fine
it's returen correct value
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
editText=(EditText)findViewById(R.id.editText);
final SharedPreferences pref = this.getSharedPreferences("Values", Context.MODE_PRIVATE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editText.setText(""+pref.getBoolean("isRunning", false));
if(pref.getBoolean("isRunning", false)==true) {
setVlaue(MainActivity.this, false);
}else {
setVlaue(MainActivity.this, true);
}
}
});
}
public void setVlaue(Context context,boolean isRunning) {
Intent intent = new Intent("my.action.MyReceiver");
intent.putExtra("isRunning", isRunning);
context.sendBroadcast(intent);
}
Setting right permissions to files (chmod +r shared_prefs shared_prefs/your_prefrences.xml) helps in most cases. But it isn't good trick.
Good solution is RemotePreferences that uses ContentProvider to access your prefs
I Want to save a message on a textView, not just to display it in another activity. For example if the application is closed the next time when will be open I want to see the message which I added.
I have two activities.
Activity one -> I save the date using SharedPraferences in the variable NAME_RESTAURANT and I sent the date throw method 'getMsg()'
Activity two -> I receive the date and I want to put it into a TextView named etWelcomeToRestaurant2
The date is represented by a string which I get it from a EditText named etDRestaurantName in first Activity.
My problem is that in SecondActivity the date is not displayed.
The activity where I save the date and from where I transmite the date to the Other activity
public class AdminAreaActivity extends AppCompatActivity {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String RESTAURANT_NAME = "restaurantName";
private String NAME_RESTAURANT;
private EditText etDRestaurantName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_area);
etDRestaurantName = findViewById(R.id.etRestaurantName);
final Button bRestaurantChange = findViewById(R.id.bRestaurantChange);
bRestaurantChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!etDRestaurantName.getText().toString().matches("")){
Intent mainIntent = new Intent(AdminAreaActivity.this,MainActivity.class);
saveData();
loadData();
etDRestaurantName.getText().clear();
startActivity(mainIntent);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(AdminAreaActivity.this);
builder.setMessage("Failed!")
.setNegativeButton("Retry", null)
.create()
.show();
}
}
});
}
public void saveData(){
SharedPreferences sharedPreferences =getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(RESTAURANT_NAME,etDRestaurantName.getText().toString()+"!");
editor.apply();
Toast.makeText(this,"Data saved!",Toast.LENGTH_SHORT);
}
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
NAME_RESTAURANT = sharedPreferences.getString(RESTAURANT_NAME,"Your Restaurant here!");
}
public String getMsg(){
return NAME_RESTAURANT;
}
}
The activity where I want to put data and where I received it:
public class MainActivity extends AppCompatActivity {
private TextView etWelcomeToRestaurant2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView etWelcomeToRestaurant = findViewById(R.id.etWelcomeToRestaurant);
String messg = "Welcome to,\n";
etWelcomeToRestaurant.setText(messg);
etWelcomeToRestaurant2 = findViewById(R.id.etWelcomeToRestaurant2);
AdminAreaActivity admOBj = new AdminAreaActivity();
etWelcomeToRestaurant2.setText(((AdminAreaActivity)admOBj).getMsg());
}
}
SharedPreferences might be the wrong way for storing data, because "It is using expensive operations which might slow down an app.". Have a look at Room for storing.
To answer your question:
Delete the loadData() method and its execution from your AdminAreaActivity, since you want to load the data in your MainActivity. Additionally you called the wrong SharedPreference name (NAME_RESTAURANT).
Only write Constants with capital letters
You can edit your saveData() and loadData() to reuse it later
See my fix below
AdminAreaActivity
public class AdminAreaActivity extends AppCompatActivity {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String RESTAURANT_NAME = "restaurantName";
private EditText etDRestaurantName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_area);
etDRestaurantName = findViewById(R.id.etRestaurantName);
final Button bRestaurantChange = findViewById(R.id.bRestaurantChange);
bRestaurantChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etDRestaurantName.getText().toString().matches("")) {
Intent mainIntent = new Intent(AdminAreaActivity.this, MainActivity.class);
saveData(RESTAURANT_NAME, etDRestaurantName.getText().toString() + "!");
etDRestaurantName.getText().clear();
startActivity(mainIntent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(AdminAreaActivity.this);
builder.setMessage("Failed!").setNegativeButton("Retry", null).create().show();
}
}
});
}
public void saveData(String prefName, String prefValue) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(prefName, prefValue);
editor.apply();
Toast.makeText(this, "Data saved!", Toast.LENGTH_SHORT);
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private TextView etWelcomeToRestaurant2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView etWelcomeToRestaurant = findViewById(R.id.etWelcomeToRestaurant);
String messg = "Welcome to,\n";
etWelcomeToRestaurant.setText(messg);
etWelcomeToRestaurant2 = findViewById(R.id.etWelcomeToRestaurant2);
etWelcomeToRestaurant2.setText(loadData(AdminAreaActivity.RESTAURANT_NAME, "Your Restaurant here!"));
}
public String loadData(String prefName, String defValue){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
return sharedPreferences.getString(prefName, defValue);
}
}
In Android, you never should be using the new operator with an Activity class.
MainActivity should instead open the same shared preference file and read the value using the same key used in AdminAreaActivity. You already have the preference file name and key as public static variables, so you can reference those variables from MainActivity.
Better yet, create a helper class to manage the preferences. Call it something like PreferenceHelper and it would look something like this:
public class PreferenceHelper {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String RESTAURANT_NAME = "restaurantName";
public static String getResturantName(Context context) {
return context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE).getString(RESTAURANT_NAME,"Your Restaurant here!");
}
public static void setResturantName(Context, String name) {
context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE).edit().putString(RESTAURANT_NAME, name).apply();
}
}
Now you can call your helper from both classes.
I am creating a restaurant app for members & non-members. The home page consist of 3 buttons- menu, sign-in and sign-up. I want to let non-members auto login (default phoneId)into the system when they tap on the menu button and members will just sign-in or sign-up each time.
I tried to use sharedPreferences (default phoneId) for the non-member auto login but I don't know whether the default phoneId can be sync with firebase. I want to track the transaction orders for the non-members. Is there any way to only let the default phoneId to have auto login function?
p/s I am just a beginner and doing this app for my project. pls help thanks.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btnSignIn, btnSignUp, btnMenu;
public AppPreferences appPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appPreference = new AppPreferences(this);
btnMenu = (Button)findViewById(R.id.btnMenu);
btnSignUp = (Button)findViewById(R.id.btnSignUp);
btnSignIn = (Button)findViewById(R.id.btnSignIn);
btnMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent home = new Intent(MainActivity.this, Home.class);
//Here save user info to preferences
appPreference.setUserPhoneId(Constant.DEFAULT_PHONE_ID);
appPreference.setUserPassword(Constant.DEFAULT_PASSWORD);
startActivity(home);
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signUp = new Intent(MainActivity.this, SignUp.class);
startActivity(signUp);
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(MainActivity.this, SignIn.class);
startActivity(signIn);
}
});
}
}
AppPreferences.java
public class AppPreferences {
// Class variables
private Context context;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
public static final String PREF_NAME = "iMenuApp";
private int PRIVATE_MODE = 0;
// Define your preferences key
private static final String USER_PHONE = "9876543210";
private static final String USER_PASSWORD = "12345";
public AppPreferences(Context context)
{
this.context = context;
sharedPreferences = this.context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
if (sharedPreferences != null)
{
editor = sharedPreferences.edit();
}
}
//Store user PhoneId
public void setUserPhoneId(String userId){
String TAG = "AppPref:setUserId";
try
{
editor.putString(USER_PHONE, userId);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
// Get userPhoneId
public String getUserPhoneId(){
return sharedPreferences.getString(USER_PHONE,"default_phone");
}
//Store userPassword
public void setUserPassword(String userPassword){
String TAG = "AppPref:setUserPassword";
try
{
editor.putString(USER_PASSWORD, userPassword);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
// Get userPassword
public String getUserPassword(){
return sharedPreferences.getString(USER_PASSWORD,"default_password");
}
}
the whole approach is rather questionable, because there is an anonymous authentication provider, which should be used for those "non-members" (and it can also be used together with security rules). storing the state of the authentication to Preferences is prone to errors, because it does not consider the actual state of the authentication - which will result in access denied, once the token expired.
I've also seen your previous question, while nevertheless the whole business logic is flawed.
... better see AccountManager, for how to properly store accounts on Android.
You need to do something like this,
MainActivity -> SignIn -> if SignIn success -> Next time you launch the app land to Home Activity
Try this,
1.) First, you define a new boolean preferences key, USER_LOGGED_IN and create setUserLoggedIn() and getUserLoggedIn() methods in your AppPreferences class as below.
private static final boolean USER_LOGGED_IN = false;
public static void setUserLoggedIn(boolean value) {
String TAG = "AppPref:setUserLoggedIn";
try{
editor.putBoolean(USER_LOGGED_IN, value);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
public static boolean getUserLoggedIn() {
return sharedPreferences.getBoolean(USER_LOGGED_IN, false);
}
2.) Then, in your SignIn Activity, If login success, set UserLoggedIn as true in your sharedPreferences.
3.) Finally, In your MainActivity, override onResume() method as follows,
#Override
protected void onResume() {
super.onResume();
boolean userLoggedIn = AppPreferences.getUserLoggedIn();
if(userLoggedIn){
MainActivity.this.startActivity(new Intent(getApplicationContext(), Home.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
}
}
Try this and let me know your feedback.
Thanks!
I want to run another application whose package name is obtained from EditText in AlertDialog. My problem is that I want to display Dialog only when PackageName has not been specified in SharedPreference or when the application is not available.
Here is my code:
public static final String mypref="mypref";
public static final String packagename="text";
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gpref();
Button b=(Button)findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View p1)
{
// TODO: Implement this method
String s=pref.getString(packagename);
if(s!=""){
Intent i=getPackageManager().getLaunchIntentForPackage(s);
if(i!=null){
startActivity(i);
} else{ sd();}
} else{
sd();
}
}
});
}
public void sd(){
final EditText et=new EditText(this);
AlertDialog ad=new AlertDialog.Builder(MainActivity.this).create();
ad.setView(et); ad.setButton(AlertDialog.BUTTON_POSITIVE,
"Set", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface p1, int p2)
{
// TODO: Implement this method
String s=et.getText().toString();
spref(s);
}
});
}
public void gpref(){
pref=getSharedPreferences(mypref,MODE_PRIVATE);
}
public void spref(String s){
gpref();
SharedPreferences.Editor spedit=pref.edit();
spedit.putString(packagename,s); spedit.apply();
}
but I did not find a way to ensure packagename at SharedPreference since packagename has not been set. Would anyone give me some ideas?
Please read official reference about getString
When specific preference does not set, the getString method would be return default value.
you could check against this default value.For example:
String s=pref.getString(packagename,"Default");
if(!s.equals("Default")){
//Do something
}