Shared preference value is null in my second acivity - java

I need to use string data inside OnReceivedDataMethod into second activity in order to save those string data into file but currently i have empty data into my file
SharedPreferences sp;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
sp = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor et = sp.edit();
et.putString("key",data);
et.apply();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
In second activity
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
desiredPreference = sharedPreferences.getString("key","data");
Toast.makeText(this,"spdata"+desiredPreference,Toast.LENGTH_LONG).show();
}

The Value is null because you used PreferenceManager.getDefaultSharedPreferences(this) which returns preference with this activity name and it's different from the other preference you used in your first activity. Instead, you should call your preference in the same way you called it in your first activity.
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String desiredPreference = sharedPreferences.getString("key","data");
To know more about the difference you can check the documentation and this answer.

Do something like this,
For storing
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", data);
editor.commit();
for Retriving
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String checkDate = sharedPref.getString("key","");

Related

Unable to clear data from sharedpreferences

This is the code of my sharedpreferences.It is working well in putting and retriving data but not able to clear data from sharedpreferences
SharedPreferences sharedPreferences1 = getSharedPreferences("userDataInSharedPref",MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences1.edit();
editor.putString("loginas", loginas_);
editor.putString("name", name_);
editor.putString("yearofbirth", yearofbirth_);
editor.putString("gender", gender_);
editor.apply();
SharedPreferences sharedPreferences1 = getContext().getApplicationContext().getSharedPreferences("userDataInSharedPref", Context.MODE_PRIVATE);
String uname = sharedPreferences1.getString("name", "");
String udob = sharedPreferences1.getString("yearofbirth", "");
String ugender = sharedPreferences1.getString("gender", "");
String uspeci = sharedPreferences1.getString("loginas", "");
UserName.setText(uname);
Birth_date.setText(udob);
Usergender.setText(ugender);
Specification.setText(uspeci);
binding.logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences1.edit();
editor.clear();
editor.commit();
// SharedPreferences sharedPreferences = getActivity().getApplicationContext().getApplicationContext().getSharedPreferences("autoLogin", Context.MODE_PRIVATE);
}
});
to clear one string :
sharedPreferences.edit().remove("name").commit();
to clear all strings :
sharedPreferences.edit().clear().apply();
Check if you are using any singleton class where you might be retrieving the values of these variables using SharedPreferences. The instance of this class need to be set to null too along with above solution.
To clear it you need to add this code
public void clear(){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}

Create Multiple Users with SharedPreferences

Hello everyone i trying a create small application. This application will keep max 3 users on it. I'm using a Sharedpreferencesfor save data. But i can't save multiple users i don't have any idea how can i do this. After creating users i want to swap between them and i don't using password for users so system will always can changeable between users.
There is my MainActivity.
public class MainActivity extends AppCompatActivity {
EditText nameText;
EditText dateText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameText = (EditText) findViewById(R.id.nameText);
dateText = (EditText) findViewById(R.id.dateText);
}
public void saveInfo(View view) {
SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username",nameText.getText().toString());
editor.putString("date",dateText.getText().toString());
editor.apply();
}
}
Thanks for your advice.
How about using a number in array to achieve this? probably something like this:
public void saveInfo(View view,User[] userList)
{
SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
for (int i = 0, i < userList.count){
User user = userList[i]
editor.putString("username-"+i,user.username);
editor.putString("date-"+i,user.date);
editor.apply();
}
}
With this, you can save three users and then call them from the sharedpreferences with username-(number of the user)
so have you tried to set different name for the sharedPreference database for each user?
public void saveInfo(View view,User[] userList)
{
for (int i = 0, i < userList.count){
User user = userList[i];
// I am creating a new shared prefence for each user!
// by their username.
SharedPreferences sharedPref = getSharedPreferences("userInfo_"+user.username.trim(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username",user.username);
editor.putString("date",user.date);
editor.apply();
}
}
After that, to get data for a specific user, you just need their username:
SharedPreferences sharedPref = getSharedPreferences("userInfo_"+user.username.trim(), Context.MODE_PRIVATE);
String userDate = sharedPref.getString("date", "unknown");
I think you should create your own Class that will hold in fields data that you will need. Also, I suggest you to create an List object instead of using array to have more comfortable options like List.size():
UserData userData = new UserData(View view, List<User> users);
Then hold it in Map with your custom unique key to easy get UserData in various usage needs:
private Map<String, UserData> userDataMap = new HashMap<>();

How to get Preferences in Android?

I don't understand how preferences work.
I have a preferences activity and one field on it:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key = "#string/pr_rest_service_url"
android:title = "#string/rest_service_url"
android:summary = "%s"
android:shouldDisableView="false"
android:selectable="true"
android:enabled="true"
android:defaultValue="543543543"
/>
</PreferenceScreen>
In preference activity i use this code to edit it:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
String editTextPrefKey = getString(R.string.pr_rest_service_url);
EditTextPreference restUrlTExtEdit = (EditTextPreference) findPreference(editTextPrefKey);
restUrlTExtEdit.getEditText().setInputType(InputType.TYPE_CLASS_TEXT);
restUrlTExtEdit.setSummary(restUrlTExtEdit.getText());
restUrlTExtEdit.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(newValue.toString());
return true;
}
});
Preference saveButton = findPreference(getString(R.string.preference_save_button));
saveButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
finish();
return true;
}
});
}
}
And its works. Works nice.
Now i want to get preferense from another parts of application. I put this code in MainActivity:
String key = this.getString(R.string.pr_rest_service_url);
SharedPreferences mSharedPreferences = getSharedPreferences(key, Context.MODE_PRIVATE);
String g = mSharedPreferences.getString(key, null);
And got null.
So how gonna work with preferences?
Or i made mistake on ths start and should not use PreferenceActivity as settings screen? Or preferenses binded to activity?
So how can i get
UPDATE
I tried
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name = sp.getString("myKey", "");
But got empty string.
Update: Use this then:
SharedPreferences yourOutputdata =
context.getSharedPreferences("YourKEY", MODE_PRIVATE); // Save as YourKEY in the Activity which you're passing data to this one ...
Because of this:
String key = this.getString(R.string.pr_rest_service_url);
You are actually getting string from resource file and saving it to preference which I believe this causes the null.
Try this:
To save:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("key","your text-data here");
editor.apply();
And to get:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("key", "");
🚩Get Android Shared Preferences from default shared preferences in java language:-
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.getString("your_key", null);
Hope this works...😊

Using SharedPreferences between Activity

I have a configuration page which has a form on it. When the button is pressed, I want to save that value to a SharedPreference. This SharedPreference value then needs to be accessed from elsewhere in my app.
I am trying to save the value like the below. I want to save the collectionID so I can use it elsewhere
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
Button mButton;
EditText mEdit;
String collectionID;
String key = "GregKey";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, collectionID);
editor.commit();
}
});
}
}
Once it has been saved, I then need to access it in another class, however I can't figure out how to do this. The example above crashes the application at the moment so something isn't quite right
I want to save the collectionID so I can use it elsewhere
Use mButton Button onClick event for saving EditText text in SharedPreferences as :
mButton.setOnClickListener( new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
// save value here in SharedPreferences
SharedPreferences settings =
ConfigPage.this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, collectionID);
editor.commit();
}
});
Your crash occurs because your value is null:
String savedID;
You need to add a value to the variable:
String savedID = "somevalue";
Also, your key is null as long as the Button is not pressed which will also lead to a crash.
The putString(String key, String value) method enables you to store a specific value with a specific key, that can later be used to reaccess the stored value.
Example:
String key = "somekey";
String value = "yourvaluetostore";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value); // store the value
editor.commit();
In another Activity:
String key = "somekey";
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
// get the value "" is default
String value = sharedPreferences.getString(key, "");
All you need in the other Activity is the key you stored the value with. With this key, you can pull the correct stored value out of the SharedPreferences. --> The key is needed to identify the value.
Since you are using the part of code :
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, savedID);
editor.commit();
Log.d("Saved as", savedID);
in the onCreate method, that translates to
...
editor.putString(null, null);
Log.d("Saved as", null);
Correct your code so that you fill those elements before. I guess you wanted to make the save in the OnClick part
Yes something its not quite right here because as i see you are saving nothing. on shared pref you should have a "key" which will be use to identify the saved value in your example it should be something like this
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public static final String COLLECTIONID_KEY = "COLLECTIONID_KEY";
Button mButton;
EditText mEdit;
String collectionID;
String savedID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
}
});
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(COLLECTIONID_KEY, collectionID);
editor.commit();
Log.d("Saved as", COLLECTIONID_KEY);
}
}
then to retrieve it :
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
String mySavedCollectionID = sharedPreferences.getString(COLLECTIONID_KEY);
and make sure that its done on the Onclick event otherwise you might end up with crash again because after the on-click event in your code the lines below will run anyway and save null!

Using share preference to save some a few int

android, java, sharedpreferences, datad during the run . What I want is that if I close or pause my app the ints value are saved, so when I open it back again I can have the last value back.
I have this so far, trying with 1 int to learn how to.
protected void onPause(){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("valueSave",valueToSave );
editor.commit();
}
#Override
protected void onResume(){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
}
But values are not saved... what am I doing wrong?
EDIT: onCreate added
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.program);
//SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//settings = getSharedPreferences(PREFS_NAME, 0);
valueToSave = settings.getInt("valueSave",valueToSave);
Try getting a SharedPreference using the application context in this way:
To save preferences:
int valueToSave = 1;
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
editor.putInt("someValue", valueToSave);
editor.commit();
To retreive from preferences:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int savedvalue = settings.getInt("someValue");

Categories

Resources