sorry for this simple question but im new to this.
I have this code:
public void English (View view) {
if (toggleButton.isChecked()) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("selectedlanguage", "English");
editor.commit();
Toast.makeText(getBaseContext(), sharedPref.getString("selectedlanguage", null) + " is the default page", Toast.LENGTH_SHORT).show();
English();
}
else English();
For later use I want to use the editor.putString("selectedlanguage", "English");"English" as class name.
Like this:
if (sharedPref.getString("selectedlanguage", null) != null) {
//use the "English" as class name so it will execute the class
}
Going off your question and comments, I'm assuming you only want to create a class based off a value stored in SharedPreferences. I'm also assuming you want to create several "languages", and launch the appropriate class from the SharedPreferences value. For that I would use the Factory pattern:
First, create a "language" interface that contains the common methods for all your language classes:
public interface Language {
//Example
void speak();
}
Second, have all your language classes implement this interface:
public class English implements Language {
#Override
public void speak() {
Log.i("Tag", "English");
}
}
public class Chinese implements Language {
#Override
public void speak() {
Log.i("Tag", "Chinese");
}
}
Third, create a Factory class that builds "language" classes:
public class LanguageFactory {
public static final int LANGUAGE_ENGLISH = 100;
public static final int LANGUAGE_CHINESE = 101;
public Language getLanguage(int code) {
Language language = null;
switch (code) {
case LANGUAGE_ENGLISH:
language = new English();
break;
case LANGUAGE_CHINESE:
language = new Chinese();
break;
}
return language;
}
}
Now, whenever you save to shared preferences, use:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("selectedlanguage", LanguageFactory.LANGUAGE_ENGLISH);
editor.commit();
And then, when you want to use the stored value:
int languageCode = sharedPref.getInt("selectedLanguage", -1);
LanguageFactory factory = new LanguageFactory();
Language language = factory.getLanguage(languageCode);
In this case, "language" will be "English", but it will change depending on the "code" you store to SharedPreferences. This is a very flexible system that will allow you to add new languages in the future, and as you use constants there is much less chance of errors caused by providing incorrect values.
Please see this
Class<?> c = null;
if(StringClassname != null) {
try {
c = Class.forName(StringClassname );
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
I want to clear the data I am getting from SharedPreference, I try the following answer but didn't make my task:
1) how to delete sharedpreferences ,Quit and launch application from first actvity in android
2) clear the value of sharedpreferences
3) Remove Shared preferences key/value pairs
4) SharedPreferences Clear/Save
they are all removing value, after they write data into SharedPreference, like editor.remove and .clear...
I have write data into SharedPreference in Notification Activity Like this:
public static final String PREFS_NAME = "com.example.sociapp";
NotificationAdapter notificationAdapter1 = new NotificationAdapter(NotificationsActivity.this, NotificationList, NKeyList);
RnotificationList.setAdapter(notificationAdapter1);
isthereItem = notificationAdapter1.getItemCount();
Toast.makeText(NotificationsActivity.this, ""+isthereItem, Toast.LENGTH_SHORT).show();
//writing data into SharedPreference
SharedPreferences.Editor editor = settings.edit();
editor.putInt("changingicon",isthereItem);
//editor.commit();
editor.clear();
editor.apply();
And I am getting this int value in MainActivity Like this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
// Reading from SharedPreferen
try {
//all I want to refresh below line everytime I start MainActivity.
int ChangeIcon = settings.getInt("changingicon", 0);
if (ChangeIcon == 0)
{
int valuebecomes = 0;
notificationIconSetting(valuebecomes);
}
else
{
int valuebecomes = 1;
notificationIconSetting(valuebecomes);
}
Toast.makeText(MainActivity.this, ""+ChangeIcon, Toast.LENGTH_SHORT).show();
}
catch (ClassCastException e){e.printStackTrace();}
The method I call, when I get int value from SharedPreference:
private void notificationIconSetting(int IconTochange)
{
if (IconTochange == 0) {
navigationView.getMenu().getItem(2).setIcon(R.drawable.notification);
}
else
{
navigationView.getMenu().getItem(2).setIcon(R.drawable.notificationalert);
navigationView.setItemIconTintList(null);
}
}
Actually I am getting an int value greater than 0 when there is a notification in the adapter, and when there is no notification in the adapter the int value is equal to 0, then I am using this value to change the notification icon.
When there is notification:
When there is no notification:
Now the problem is whenever I get a value, it remains the same until I clear app cache or Uninstall and then install again.
All I want to refresh the SharedPreference value every time I start MainActivity.
You want to remove one key/value from shared preference
here's how i do it.
public void clearSpecificKey(String key){
sharedPreferences.edit().remove(key).apply();
}
Few things to note :
You should create a generic class of Shared Preference Like below
public class SharedPrefs {
private static final String MY_PREFS_NAME = "YOUR-PREFERENCE-NAME";
private static SharedPreferences sharedPreferences;
private String masterKeyAlias;
public SharedPrefs(Context context) {
{
try {
masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
try {
sharedPreferences = EncryptedSharedPreferences.create(MY_PREFS_NAME,masterKeyAlias,context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
public String getStrings(Context mContext, String key){
return sharedPreferences.getString(key, null);
}
public void putString(Context mContext, String key, String value ){
sharedPreferences.edit().putString(key, value).apply();
}
public boolean getBoolean(Context mContext, String key){
return sharedPreferences.getBoolean(key, false);
}
public void putBoolean(Context mContext, String key, boolean value ){
sharedPreferences.edit().putBoolean(key, value).apply();
}
public static void clear(Context mContext){
sharedPreferences.edit().remove("user").apply();
}
public void clearSpecificKey(String key){
sharedPreferences.edit().remove(key).apply();
}
}
Here how to use it
Declaration :
SharedPrefs sharedPrefs;
Initialization :
sharedPrefs = new SharedPrefs(context);
just call the methods you want to use to store value in shared preference like
sharedPrefs.putString(context,key,value)
masterKeyAlias is to secure my Shared preferences.
Add this your app gradle
implementation "androidx.security:security-crypto:1.0.0-beta01"
you can read more about it here Best Practices
I have an app that basically looks like the design in the attached picture.
As you can see, there are 4 activities, and some of the activities have fragments.
I want to get the answer of a test back to the user's profile.
Up to now, I've been uploading the result to the server and having the app update the user's profile every time they go back to the ProfileActivity, but that seems like a waste of resources.
Is there a pattern or way to do this in the app?
I looked at this: which seems doable if I can somehow link two startActivityForResult()s.
I looked into using the delegate pattern described in this question but I can't get the instance of the UserFragment to the TestActivity.
I hope someone can point me in the direction of the correct way of doing this.
One approach is use startActivityForResult() don't finish any Activity
start all activities by startActivityForResult() then depending on your condition you can finish activity
pass result back to the previous activity using onActivityResult()
Then for fragment you can store fragment object in ProfileActivity .
In Fragment write method for updating UI
So you can access that method using fragment object
class ProfileActivity extends ......
{
#override
public void onActivityResult(....)
{
.....
frgamnetObject.updateUI();
....
}
}
Assuming that you are getting one int value from last page:
create class :
public class GenericUtility {
public static int getIntFromSharedPrefsForKey(String key, Context context)
{
int selectedValue = 0;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
selectedValue = prefs.getInt(key, 0);
return selectedValue;
}
public static boolean setIntToSharedPrefsForKey(String key, int value, Context context)
{
boolean savedSuccessfully = false;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try
{
editor.putInt(key, value);
editor.apply();
savedSuccessfully = true;
}
catch (Exception e)
{
savedSuccessfully = false;
}
return savedSuccessfully;
}
public static String getStringFromSharedPrefsForKey(String key, Context context)
{
String selectedValue = "";
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
selectedValue = prefs.getString(key, "");
return selectedValue;
}
public static boolean setStringToSharedPrefsForKey(String key, String value, Context context)
{
boolean savedSuccessfully = false;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try
{
editor.putString(key, value);
editor.apply();
savedSuccessfully = true;
}
catch (Exception e)
{
savedSuccessfully = false;
}
return savedSuccessfully;
}
}
than to set int value to it:
GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, getApplicationContext());
or
GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, MyActivity.this))
and in your very first activity where you want result:
int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", getApplicationContext());
or
int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", MyActivity.this);
selectedValue will return default value if there is no value in it.
PS change int to String in class to get and set result accordingly.
Here is my Contacts activity (my main activity):
public class Contacts extends Delegate {
private static final String TAG = "Contacts";
public View listContactsView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("token", null);
if(restoredText == null)
{
Intent intent = new Intent(this, SignIn.class);
startActivity(intent);
}
setContentView(R.layout.activity_contacts);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ContactListFragment()).commit();
}
//new InEventAPI(this).execute("");
}
...
...
Here is my SignIn activity:
public SignIn extends Delegate {
...
...
public void personSignInDelegate(HttpResponse response, JSONObject result)
{
if(response != null && result != null)
{
switch(response.getStatusLine().getStatusCode())
{
case 200:
try {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("token", result.get("tokenID").toString());
editor.commit();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 401:
Toast.makeText(this, R.string.toastEmailPasswordIncorrect, Toast.LENGTH_LONG).show();
break;
}
}
else
{
Log.d(TAG, "Something went wrong!");
}
}
When I sign in, it commits on SharedPreferences, but when I close my app and re-open, the String becomes null and my OnCreate intents to SignIn again.
Is something that I'm missing?
Just to avoid doubts, my Delegate class:
public class Delegate extends ActionBarActivity {
protected InEventAPI api;
public Delegate() {}
public void personSignInDelegate(HttpResponse response, JSONObject result) {};
}
The problem is most likely with your use of getPreferences(). From the documentation:
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity. This simply calls the underlying
getSharedPreferences(String, int) method by passing in this activity's
class name as the preferences name.
Although both classes extend the Delegate class, they are both unique classes with unique names. This means that getPreferences() in Contacts returns a different SharedPreferenceObject compared to SignIn.
Either use getSharedPreferences(String, int)
Eg.
instead of
getPreferences(MODE_PRIVATE);
change it to
getSharedPreferences ("OneSharedPreference", MODE_PRIVATE);
or override getPreferences() in Delegate so it calls getSharedPreferences() with a unique name.
Alternatively, if you're not using the default SharedPreferences for anything (this is usually used by any PreferenceActivity classes), you can always call
PreferenceManager.getDefaultSharedPreferences() and pass in a Context instance.
Can anybody tell me how to maintain session for a user login. For example when the user sign- in to an application they have to be signed in unless the user logouts or uninstall the application similar to gmail in android.
Make one class for your SharedPreferences
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
Now after making this class when you want to use it, use like this: make object of this class like
private Session session;//global variable
session = new Session(cntx); //in oncreate
//and now we set sharedpreference then use this like
session.setusename("USERNAME");
now whenever you want to get the username then same work is to be done for session object and call this
session.getusename();
Do same for password
You can achieve this by using AccountManager.
Code Sample
// method to add account..
private void addAccount(String username, String password) {
AccountManager accnt_manager = AccountManager
.get(getApplicationContext());
Account[] accounts = accnt_manager
.getAccountsByType(getString(R.string.account_type)); // account name identifier.
if (accounts.length > 0) {
return;
}
final Account account = new Account(username,
getString(R.string.account_type));
accnt_manager.addAccountExplicitly(account, password, null);
final Intent intent = new Intent();
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
intent.putExtra(AccountManager.KEY_PASSWORD, password);
intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,
getString(R.string.account_type));
// intent.putExtra(AccountManager.KEY_AUTH_TOKEN_LABEL,
// PARAM_AUTHTOKEN_TYPE);
intent.putExtra(AccountManager.KEY_AUTHTOKEN, "token");
this.setAccountAuthenticatorResult(intent.getExtras());
this.setResult(RESULT_OK, intent);
this.finish();
}
// method to retrieve account.
private boolean validateAccount() {
AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> arg0) {
Log.e("calback", "msg");
try {
Bundle b = arg0.getResult();
if (b.getBoolean(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE)) {
//User account exists!!..
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
AccountManager accnt_manager = AccountManager
.get(getApplicationContext());
Account[] accounts = accnt_manager
.getAccountsByType(getString(R.string.account_type));
if (accounts.length <= 0) {
return false;
} else {
loginNameVal = accounts[0].name;
loginPswdVal = accnt_manager.getPassword(accounts[0]);
return true;
}
}
I have one simple way rather than maintain a session.
i.e. Just store one boolean variable with your username and password. by default set value equal to false.
After first successful login make its value to true.
Then just check its value on your Mainactivity, if it is true then jump to next activity otherwise jump to login activity.
You can use a boolean value in the SharedPreferences.
Load it before login to check if login is needed.
Save it after login.
Use SharedPreferences.
Code to save a value to sharedpreferences:
SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
SharedPreferences.Editor ed=sp.edit();
ed.putInt("value", your_value);
ed.commit();
Code to get value from sharedpreferences:
SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
int value = sp.getInt("value", default_value);
You can check login and logout by using this value.
You can obtain that behaivour in a few different ways, the one I prefer is setting a flag in the shared prefs. whe a user logs in an check it when the app is started if you get the default value the user is not loggend, else you should have your flag (i use the user name) set and avoid the log-in section.
save the user data in shared preferences till the user logs out.
once user logs out clear the data from shared preferences.
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
editor = prefs.edit();
}
public void setusename(String usename) {
editor.putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUcUZxeHo0UnJ5UHc
Fetch Previous Login ID in android
**After Login save Email ID is SharedPreferences**
emaidId = et_Email.getText().toString().trim();
SharedPreferences ss = getSharedPreferences("loginSession_key", 0);
Set<String> hs = ss.getStringSet("set", new HashSet<String>());
hs.add(emaidId);
SharedPreferences.Editor edit = ss.edit();
edit.clear();
edit.putStringSet("set", hs);
edit.commit();
===================onCreate()====================
===================AutoCompleteTextView set Adapter===================
**Fetch PRevious Login Email id in email EditText**
SharedPreferences sss = getSharedPreferences("loginSession_key", 0); // todo loginSession_key key name ALWAYS SAME
Log.i("chauster", "2.set = " + sss.getStringSet("set", new HashSet<String>()));
Log.e("Session", "Value->" + sss.getStringSet("set", new HashSet<String()));
ArrayList<String> al = new ArrayList<>();
al.addAll(sss.getStringSet("set", new HashSet<String>()));
//Creating the instance of ArrayAdapter containing list of language names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, al);
//Getting the instance of AutoCompleteTextView
et_Email.setThreshold(1);//will start working from first character
et_Email.setAdapter(adapter);//setting the adapter data into the
Using this class will help you to store all types of sessions
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void set(String key,String value) {
prefs.edit().putString(key, value).commit();
}
public String get(String key) {
String value = prefs.getString(key,"");
return value;
}
}
Through this format, you can set or get multiple objects of data, you don't need to create separate functions to store different models in SharedPreferences.
* Here in this format, you don't need to pass your object KEY for putString() and getString()
* Using the object class name you are able to identify your session object uniquely, for both setModel() and getModel()
public class Session {
private final SharedPreferences pref;
public Session(Context ctx) {
pref = PreferenceManager.getDefaultSharedPreferences(ctx);
//pref = ctx.getSharedPreferences("IDENTIFIED_NAME", Context.MODE_PRIVATE);
}
public <U> void setModel(U obj) {
pref.edit().putString(getClassName(obj), SerializeObject(obj)).apply();
}
/* Parameter Example: Class.class */
public <U> U getModel(Class<U> type) {
String user = pref.getString(type.getSimpleName(), null);
if (isEmptyOrNull(user)) {
return null;
}
return DeserializeObject(user, type);
}
/* The below functions are for support, You can move the below part to your own BaseUtil class. */
public static boolean isEmptyOrNull(String data) {
if (data == null) {
return true;
}
if (data.isEmpty() || data.trim().isEmpty()) {
return true;
}
return false;
}
public static String getClassName(Object obj) {
return obj.getClass().getSimpleName();
}
public static String SerializeObject(Object myObject) {
// serialize the object
try {
Gson gson = new Gson();
String json = gson.toJson(myObject);
return json;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public static <U> U DeserializeObject(String serializedObject, Class<U> type) {
// serialize the object
try {
if (serializedObject == null || serializedObject.isEmpty()) {
return null;
}
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
U data = gson.fromJson(serializedObject, type);
return data;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
}
Create an object class (file_name: UserModel.java)
public class UserModel {
public String userId;
public String firstName;
public String lastName;
public String email;
public String phone;
}
How to use - For setModel() and getModel()
//creating an instance of the Session class
Session session = new Session(ctx); // Here you have to pass the Context(ctx)
// setting value in the UserModel
UserModel obj = new UserModel();
obj.firstName = "Apu";
obj.lastName = "Pradhan";
obj.email = "godfindapu#gmail.com";
obj.phone = "123456789";
// set UserModel in the Session
session.setModel(obj);
//getting UserModel data from the Session
UserModel userData = session.getModel(UserModel.class);
i have created a sharedpreferences data in one activity, is it possible to be used in another activity? if yes, how could this be achieved?
The names of the 4 players are saved in NameIndex.java, and I would like to use the saved Names of the 4 players in the MainActivity.java
Under NameIndex.java:
private void SaveNamesToFile(String Game1, String P1Name, String P2Name, String P3Name, String P4Name)
// save the new row to the file, then refresh all Buttons
{
// originalScore will be null if we're modifying a slot that is existing already
String originalNameP1 = SavedNameP1.getString(Game1, null); // to return null if this preference does not exist.
String originalNameP2 = SavedNameP2.getString(Game1, null);
String originalNameP3 = SavedNameP3.getString(Game1, null);
String originalNameP4 = SavedNameP4.getString(Game1, null);
// get a SharedPreferences.Editor to store new row data
SharedPreferences.Editor preferencesEditorP1 = SavedNameP1.edit();
SharedPreferences.Editor preferencesEditorP2 = SavedNameP2.edit();
SharedPreferences.Editor preferencesEditorP3 = SavedNameP3.edit();
SharedPreferences.Editor preferencesEditorP4 = SavedNameP4.edit();
preferencesEditorP1.putString(Game1, P1Name);
preferencesEditorP2.putString(Game1, P2Name);
preferencesEditorP3.putString(Game1, P3Name);
preferencesEditorP4.putString(Game1, P4Name);
preferencesEditorP1.apply();
preferencesEditorP2.apply();
preferencesEditorP3.apply();
preferencesEditorP4.apply();
}
I used one SharedPreferences file between activities, but what I did was using the same file name declared in different private variables inside the two activities. You can check my code in the following link. What I don't understand is why you use 4 SharedReferences files just for the names of the players and not all the names in just 1 file. That's possible because I used it to save more than 2 variables.
Yes they can be shared across activities. The easiest route is to just use:
context.getDefaultSharedPreferences()
I am using it like this
public class SharedPreferencesHelper {
SharedPreferences myPrefs;
SharedPreferences.Editor prefsEditor;
private static SharedPreferencesHelper instance = null;
public static synchronized SharedPreferencesHelper getInstance() {
if (instance == null) {
instance = new SharedPreferencesHelper();
}
return instance;
}
private SharedPreferencesHelper() {
myPrefs = MyApplication.getInstanse().getApplicationContext().getSharedPreferences("prefs", Context.MODE_WORLD_READABLE);
prefsEditor = myPrefs.edit();
}
public void putValueForKey(String key, String value) {
prefsEditor.putString(key, value);
prefsEditor.commit();
}
}
public class MyApplication extends Application {
private static MyApplication instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static MyApplication getInstanse(){
if(instance ==null){
throw new IllegalStateException("Application not created yet!");
}
return instance;
}
}