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<>();
Related
I am new at programing in Java and I am taking a course of Android application. I am building a button inside an activity. But when I exit the activity, the button changes to it's original state. I know I am not doing anything to save its state, but how do I do it?
Here is the xml file (only the button part):
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Catch"
android:id="#+id/button"
android:onClick="toggleCatch" />
And here is toggleCatch:
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
}
What could I do to make it work?
you should store the data that indicate on it state in some place:
1. SQLlite
2. Server
3. SharedPreference
and then when you create the activity you set the state of the btn based on the data you loaded.
if you do it just for practice, I believe that the sharepreference will be just fine.
https://developer.android.com/training/data-storage/shared-preferences
to store any data locally in the sharedPreference:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", trueOrFalse);
editor.commit();
to get the saved data:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean stateBtn = sharedPref.getBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", defaultValueForExTrue);
sharedPref.getBoolean can be used also for sharedPref.getString, sharedPref.getInt Etc..
hope that helped..
My recommendation for you is to read about the subjects above.(SQLlite, SharedPreference)
You need to save button state in persistent storage; there are several types of persistent storage that Android supports, like SharedPreference, DataBase, internal/external storage File... The most appropriate for your question is the SharedPreference as it stores small data.
To achieve that in your code sample
public static final String PREFS_NAME = "PREFS_NAME";
public static final String BUTTON_STATUS = "status";
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(BUTTON_STATUS, isCaught);
editor.apply();
}
And you need to retrieve the value again from the shared preference when the app is launched, so in your activity onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
isCaught = prefs.getBoolean(BUTTON_STATUS, false);
if (isCaught) {
button.setText("Release");
} else {
button.setText("Catch");
}
}
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.
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","");
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!
The title is the question. I have saved a string value in the shared preference and i was able to access it in that class. Now i want to access it from a another method of another class. Tried some ways but didn't work.
The class that saves string inside shared preference:
http://pastie.org/4254511
Class trying to retrieve the username that was previously save in shared preference:
public class testSharedPrefernce extends Activity{
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lo);
tv = (TextView)findViewById(R.id.textView1);
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String name = myPrefs.getString("NAME", "YourName");
tv.setText(name);
}
}
Just make a constructor of that class which accepts the context.As example:
class Abc
{
Context contaxt;
public Abc(Context context)
{
this.context = context;
}
}
..........
..........
// now use this context to SharedPref..
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
Use below code for get preferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
boolean cbvalue = myPrefs.getBoolean("CHECKBOX", false);
String name = myPrefs.getString("NAME", "YourName");
String paswrd =myPrefs.getString("PASSWORD", "123");
Use below code for save preferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("NAME", "Dipak");
prefsEditor.putString("PASSWORD", "Dipak123");
prefsEditor.commit();