I need to generate random int to give device id when my app run for the first time, then save it to SharedPreffs, show id on TextView, and when is turned on again show saved id from SharedPreffs on TextView.
public class MainActivity extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs";
public static final String KEY_DEVICE = "id";
SharedPreferences sharedpreferences;
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceid = (TextView) findViewById(R.id.deviceid);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (!sharedpreferences.contains(id)) {
SharedPreferences.Editor editor = sharedpreferences.edit();
id = String.valueOf(new Random().nextInt(900000) + 100000);
editor.putString(KEY_DEVICE, id);
editor.commit();
deviceid.setText(id);
}
deviceid.setText(id);
}
}
Above code generates random int and show it on TexView, but every time I hide or turn off the app, the device id changes
Could you explain me what i have to do to achive my goal.
There should be "id" or KEY_DEVICE
Replace
!sharedpreferences.contains(id)
to
!sharedpreferences.contains(KEY_DEVICE)
Also
deviceid.setText(id);
will show null in that case
So you have to add before setText
id = sharedpreferences.getString(KEY_DEVICE,"0");
Try this
String MyPREFERENCES = "MyPrefs";
String KEY_DEVICE = "device_id";
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(KEY_DEVICE)) {
id = sharedpreferences.getString(KEY_DEVICE, "0");
deviceid.setText(id);
} else {
id = String.valueOf(new Random().nextInt(900000) + 100000);
editor = sharedpreferences.edit();
editor.putString(KEY_DEVICE, id);
editor.apply();
deviceid.setText(id);
}
This is because you are just checking if there is no shared preference value then select a random number and add it to device but you are not getting any value in the on create method i.e you are not getting any shared preference value that you stored before. Simply get your stored value and then check if the value is exist, if exists then set in textview otherwise call the condition check. Hope it Helps
Put a check for null before fetching the value from sharedPreferences.
If it is null : then save the id
else : fetch the older one only.
If this check : if(!sharedpreferences.contains(id)) is required then keep it nested under null check.
Related
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<>();
I have problem with sharedpreferences, something goes wrong and I always get a default value.
My sharedpref class is:
public class IntolleranceData {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
}
I save value in Activity by:
intolleranceData = getApplicationContext().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something").apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG).show();
and this is great (toast shows correct string -"fish: something") but if I try to use sharedpreferences in fragment (in the same Activity and SharedPreferences, Activity and Fragment are in the same package) by:
intolleranceData = getActivity().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
It shows "fish: 00000" so this is default value...
Is there any way to solve my problem?
Try checking to make sure that your GetActivity() isn't null before you reference it to return the SharedPreferences.
Also, you are using 'apply()' to add your changes to the SharedPreferences, which is a process which runs in the background. If you try and read from the data too early (e.g. simultaneously) then you can often get the default value. Alternatively, use .commit() to save your changes to the SharedPreferences.
Finally, if the problem is unrelated to either of these common issues, saving 'getActivity().getApplicationContext()' to a variable when the fragment is initialized, it should help with the problem of the context not linking correctly!
Best of Luck!
There is need to change your file like this, In the Place of
intolleranceData = getActivity().getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
You Must change Your code Like this, way,.... and also you just simply change your getActivity() with className.this
intolleranceData = MainActivity.this.getSharedPreferences("intolleranceData", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
String myKey = intolleranceData.getString(FISH_KEY,"error");
introlleranceEditor.commit();
introllerenceEditor.apply();
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
You don't need editor to read data.
When you send data use
intolleranceEditor.putString(FISH_KEY, "something");
intolleranceEditor.commit();
I got your Problem i will give you a Perfect answer for your problem simply check this code......
public class MainActivity extends AppCompatActivity {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
static final String File_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intolleranceData = MainActivity.this.getSharedPreferences("File_Name", Context.MODE_PRIVATE);
String myKey = intolleranceData.getString(FISH_KEY,"");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
}
}
and in Shared Preferece or Inside button Click you can write this code
intolleranceData = MainActivity.this.getSharedPreferences("File_Name", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something")
intolleranceEditor.commit();
intolleranceEditor.apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG)..show();
If you Solve your problem give a simple response
I understand that you trying to use this code display a message in the Fragment kk, try this code.....
public class MainActivity extends AppCompatActivity {
static SharedPreferences intolleranceData;
static SharedPreferences.Editor intolleranceEditor;
static final String FISH_KEY="00000";
static final String File_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intolleranceData = getActivity().getSharedPreferences("File_Name", Context.MODE_PRIVATE);
String myKey = intolleranceData.getString(FISH_KEY,"");
Toast.makeText(getActivity(),"fish: "+myKey,Toast.LENGTH_LONG).show();
}
}
and In Shared Prefereces
intolleranceData = getApplicationContext().getSharedPreferences("File_Name", Context.MODE_PRIVATE);
intolleranceEditor = intolleranceData.edit();
intolleranceEditor.putString(FISH_KEY, "something")
intolleranceEditor.commit();
intolleranceEditor.apply();
Toast.makeText(getApplicationContext(), "fish: " + intolleranceData.getString(FISH_KEY, "error"), Toast.LENGTH_LONG)..show();
You should commit after you add the string...
intolleranceEditor.putString(FISH_KEY, "something");
intolleranceEditor.commit();
I have a radiogroup with two radio buttons. I want to select one radio button and hit save so that when I return the same radiobutton will be selected already. The problem is that even after I hit save the sharedpreferences in onCreate always returns null. I know that the save function is executing because the toast runs and I get the System.out.println printed in my console.
public void saveSettings(View view)
{
Toast.makeText(getApplicationContext(), "Settings Saved", Toast.LENGTH_LONG).show();
//DETERMINE WHICH RADIO BUTTON IS SELECTED
RadioButton lbSetting = (RadioButton)findViewById(R.id.weightSettingLB);
RadioButton kgSetting = (RadioButton)findViewById(R.id.weightSettingKG);
if(lbSetting.isChecked())
{
weightSetting = "lb";
}
if(kgSetting.isChecked())
{
weightSetting = "kg";
}
System.out.println("The " + weightSetting + " radio button has been selected.");
//SAVE WEIGHT SETTING BETWEEN LB/KG
settingsPrefString = getSharedPreferences(weightSetting, 0);
SharedPreferences.Editor editor = settingsPrefString.edit();
editor.putString("weightSetting", weightSetting);
editor.commit();
}
In my onCreate I try to retrieve the saved data as
if(settingsPrefString != null)
{
weightSetting = settingsPrefString.getString("weightSetting", "Couldn't load data!");
}
if(settingsPrefString == null)
{
System.out.println("settingsPrefString is NULL!");
}
Even after I hit save the sharedpreferences is always being returned as null.
Call these functions when you need them:
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("weightSetting", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private String loadPreferences(String key){
SharedPreferences sharedPreferences = getSharedPreferences("weightSetting", MODE_PRIVATE);
String load = sharedPreferences.getString(key, "");
return load;
}
}
For example:
savePreferences("selected", "lb");
and
String s = loadPreferences("selected);
The mistake you are doing is inside saveSettings method. While creating a shared preference for the first you are not assigning a constant name to it since you have used variable for name so change it. Create a global string constant for same
//SAVE WEIGHT SETTING BETWEEN LB/KG
settingsPrefString = getSharedPreferences(weightSetting, 0);
SharedPreferences.Editor editor = settingsPrefString.edit();
to
public static final String SETTINGS_PREFERENCE = "SETTINGS_PREFERENCE"
SharedPreference settingsPrefString
//your code
//saveSettings method
//SAVE WEIGHT SETTING BETWEEN LB/KG
settingsPrefString = getSharedPreferences(SETTINGS_PREFERENCE , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settingsPrefString.edit();
if you look in the change then two constant are used which makes code more readable and accessable.
Also next time inside your onCreate() method you will have to add
settingsPrefString = getSharedPreferences(SETTINGS_PREFERENCE , Context.MODE_PRIVATE);
if(settingsPrefString != null)
{
weightSetting = settingsPrefString.getString("weightSetting", "Couldn't load data!");
} else {
System.out.println("settingsPrefString is NULL!");
}
Replace
settingsPrefString = getSharedPreferences(weightSetting, 0);
With
settingsPrefString = getSharedPreferences(weightSetting, Context.MODE_PRIVATE);
This will also help
settingsPrefString = PreferenceManager.getDefaultSharedPreferences(this);
and follow this link
On my main activity I'm looking into a variable, if the variable contains a string ("example string") then it will go to the home-screen. if the variable contains nothing ("") it will redirect them to a page where they can enter a value via an editText and then permanently store it. So the next time they open the app, it will have this permanent string (until the app is deleted) and therefore it will just go to the home-screen.
From research i understand that i may have to use Shared Preferences. I have tried this already and I think im not doing something right.
Please could someone illustrate with a code example of what needs to be done for the code i have posted.
MainActivity.class
//this class uses the string, to see if its blank or contains a string
public class MainActivity extends Activity {
public static final String Verified = ""; //Originally comes blank
private EditText NumberET; //editText for user to enter a string
//the string verified is used in the main activity to determine which xml file to open.
Verified.class
// this is the class used to enter the string and permanently store it
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);
Button VerifyCompleteButton = (Button) findViewById(R.id.VerifyCompleteButton);
VerifyCompleteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String Verified;
String Number;
Bundle bundle = getIntent().getExtras();
Verified = bundle.getString("Verified");
NumberString = bundle.getString("NumberString")
Verified = NumberString.toString(); //set String Verified permenantly
}
});
You may use like this , Very much similar to above answer
For Saving String
SharedPreferences sharedPref = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Verified", Verified);
editor.commit();
For getting string
SharedPreferences shared = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
String keyReturn = shared.getString(key, "");
Log.d("return value" , "Verified is " + verified);
Great example of using SharedPreference can be found on Google's Android developer website.
Saving data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", "VALUE");
editor.commit();
Get data:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
String savedValue = context.getString("KEY", "");
Things to look after:
Make sure your [key] is the same for saving and getting. The shared preferences is a basically a hashmap/dictionary.
When getting use the second parameter to set a default return value when setting isn't found or set yet.
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!