I am grabbing a String from text file on a url and saving it to sharedPreferences ... then the next time it grabs the String, it compares it against the old one stored in shared preference and if its different it notifies the user.
I am getting the string from url fine and its saving in sharedPreferences, but when I try to compare them with an if (x == y) statement it always results as not the same;
Here is the onPostExecute()
protected void onPostExecute(String result) {
String Input;
String oldInput;
Input = result.toString();
oldInput = currentSavedSettings();
if (Input == oldInput){
Toast.makeText(MainActivity.this, "fixed", Toast.LENGTH_LONG).show();
} else {
savePrefs("CURRENT_SETTINGS_FILE", Input);
//the toasts were used to ensure that neither were returning null
Toast.makeText(MainActivity.this, oldInput, Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, Input, Toast.LENGTH_LONG).show();
// the following is commented out until I fix this issue
//createNotification();
}
}
and the currentSavedSettings which is getting the old CURRENT_SETTINGS_FILE
private String currentSavedSettings() {
SharedPreferences sp =
PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String result = sp.getString("CURRENT_SETTINGS_FILE", null);
return result;
}
and for good measure here is what i am using to save the SharedPreference
private void savePrefs(String key, String value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
Use .equals or .equalsIgnoreCase to compare strings.
For more info
How do I compare strings in Java?
Did you try this,
passcode == pref_passcode // is not the same according to Java
String passcode;
pref_passcode.contentEquals(passcode); //try this or
pref_passcode.equals(passcode)
You should always use one of these to compare string. do not use equal signs (==)
Related
I am facing an issue with saving an object boolean in SharedPreferences. The object (part of ArrayList "questions") contains a boolean "recentAnswer".
If I change the boolean value and want to use it in another activity, the value is still the old one.
Here is my saveData-method from Activity 1:
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(questions);
editor.putString("task list", json);
editor.apply();
}
and here's where I use it in order to save the changed boolean value (Activity 1):
private void checkAnswer(Button answerButton){
if (answerButton.getText().equals(questions.get(currentQuestion).getAnswer1())){
questions.get(currentQuestion).recentAnswer = true;
}
else{
questions.get(currentQuestion).recentAnswer = false;
}
Toast.makeText(this, Boolean.toString(questions.get(currentQuestion).recentAnswer), Toast.LENGTH_SHORT).show();
saveData();
}
Firstly, I load the ArrayList in Activity 2:
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<Question>>(){}.getType();
questions = gson.fromJson(json, type);
if(questions == null){
questions = new ArrayList<>();
}
}
And then I want to get the "recentAnswer" values (Activity 2):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics);
loadData();
for (Question element : questions){
int recentWrong;
if (!element.recentAnswer){
recentWrong++;
}
}
Toast.makeText(this, Integer.toString(recentWrong), Toast.LENGTH_SHORT).show();
}
No matter, how I change the values in Activity 1, in Activity 2 "recentWrong" is always = 0, even though I am accessing the questions.
Don't do this:
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(questions);
editor.putString("task list", json);
Do not do this ever. First off is you are not checking and do not know what the value questions may hold and you also should not save something like that in SharedPrefs.
If you have several questions, then save each question together with its response in SharedPrefs and if you need to save an answer that you want to check against later in code, use string values stored in the res->strings.xml.
If the question is too long, find a way to concat it or use the res->string-arrays.xml and keep the questions there, then reference them from there.
You need to go back a bit and take a look at how to design programs in Java, Kotlin or any language for that matter. This is what comes after you learn programming basics.
I am new to Android App Development and I am supposed to make a TodoList App for a course. But the SharedPreference in my code is not working. I dont know if I'm supposed to use it in a specific way in a specific method like onCreate or onStop.
It is saving the first input the user is entering permanently, but in the same position:
(The "task0" is what I used to track the different variable names I used as argument for "putString" in addStuff method, to avoid replacing values)
It is saving the inputs after that in the same session, but if the user ends that session, all those values after "t" are gone. If the user restarts the app and inputs something else (like "g"), it is saving "g" in that same 3rd position.
I have basic Java knowledge and I tried to understand what is going on using it, but failed. Please let me know where is the mistake and how to use SharedPreferences properly.
public class TodoActivity extends AppCompatActivity {
public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
taskBox = (EditText) findViewById(R.id.box);
s = taskBox.getText().toString();
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
//add items to list
items.add("First Item");
items.add("Second Item");
//restore
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
//checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
String dummyname = "task";
text.setText(String.valueOf(counter));//since counter is again at
for(int c=0; c<=50; c++){
String num = String.valueOf(c);
dummyname = dummyname + num;
String x = sp.getString(dummyname, "not found");
if (x.equalsIgnoreCase("not found")){
counter=c-1;
break;
} else {
items.add(x);
text.setText(dummyname);
}
}
}
public void addItem(View v){
s = taskBox.getText().toString();
itemsAdapter.add(s);//adding the new task as string
String temp = String.valueOf(counter);
newtask = "task" + temp;
//trying to store the new tasks with different variable names to avoid being replaced
text.setText(newtask);
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
SharedPreferences.Editor e = sp.edit();
e.putString(newtask,s);
e.apply();
counter++;
}
}
If you have relatively small collection of key-values that you would like to save,
You should use Shared preference API
Read from the shared preference:
Pass the key and value you want to write,create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass key and values you want to save by using this method putInt() ,putString() ,Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();
Write from the shared preference:
To retrieve values from a shared preferences file, call methods such as getInt() and getString(),
providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);
Two things :
1) To initialize SharedPreferences use :
sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
2) Where are you calling addItem() method??
The problem is about the Tag you use to save items. See this Line :
dummyname = dummyname + num;
You add item by this format :
task0
task1
task2
but you are getting values in this format
task0
task01
task012
Just change these two line of code :
//dummyname = dummyname + num;
//String x = sp.getString(dummyname, "not found");
String newDummy= dummyname + num;
String x = sp.getString(newDummy, "not found");
I made a chat room app which asks the user to enter its username every time i open it. How can i make it remember me? I am using fire-base for the back end.
See Code Here
Create Shared Preference class where first time when user enter his/her username store it.
You can read more about Shared Preference here
The for you as follows
public class SharePref {
public static final String PREF_NAME = "chatroom.shared.pref";
public static final String PREF_KEY = "chatroom.shared.username";
public SharePref() {
}
public void save(Context context, String text) {
SharedPreferences sharePref;
SharedPreferences.Editor editor;
sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
editor = sharePref.edit();
editor.putString(PREF_KEY,text);
editor.apply();
}
public String getData(Context context) {
SharedPreferences sharePref;
String text;
sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
text = sharePref.getString(PREF_KEY,null);
return text;
}
}
Now in your MainActivity you can check if you have already stored the username for user
inside your onCreate()
SharePref sharePref = new SharePref();
String UserName = sharePref.getData(mContext);
if(UserName == null) {
String value = //username value;
SharePref sharePref = new SharePref();
sharePref.save(context,value);
}
else {
// you already have username do your stuff
}
Hope this will help
You can use shared preference. Say you are saving username in String called User. To save username:
SharedPreferences shareit = getSharedPreferences("KEY",Context.MODE_PRIVATE);
SharedPreferences.Editor eddy = shareit.edit();
eddy.putString("AKEY", User);
eddy.commit();
And everytime user login:
SharedPreferences sharedPreferences = getContext().getSharedPreferences("KEY", Context.MODE_PRIVATE);
String getName = sharedPreferences.getString("AKEY", "");
String getName will have the value of your username. The "KEY" and "AKEY" used above are to give special id to different values saved via shared preference.
SharedPreferencec prefs = getSharedPreferences("username",Context.MODE_PRIVATE);
SharedPreference.Editor editor = prefs.edit();
if (!prefs.getString("username",null)
//do the chatting
else {
//show dialog to get username
//now save it in shared preferences
editor.putString("username",username);
editor.commit();
}
I am using SharedPreference in my Android app to store a string value, but it always takes the defValue from .getString(String key, String defValue), despite having a set value.
Here is my code:
public class AddAlert extends Activity {
[...]
public static final String LAST_ALERT_TIME = "1414931472952";
[...]
public boolean checkIfMoreThanTenMinutesFromLastAlert() {
SharedPreferences lastAlertTimeSettings = getSharedPreferences(LAST_ALERT_TIME, 0);
String lastAlertTime = lastAlertTimeSettings.getString(LAST_ALERT_TIME, null);
double currentDate = new Date().getTime();
if (getDifference(currentDate, Double.valueOf(lastAlertTime))/1000/60>10) {
return true;
} else return false;
}
public double getDifference(double currentDate, double lastAlertDate) {
//milliseconds
double difference = currentDate - lastAlertDate;
return difference;
}
}
The problem is that LAST_ALERT_TIME has a preset value, but it always returns the defValue("null" in this case").
Is there anything wrong I am doing?
Thank you!
before you GET a preference in your app,
make sure you set the source of data
provide a real value for your key that you are getting
PreferenceManager.setDefaultValues(this, R.xml.default_values, false);
SharedPreferences.Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
ed.putString("LAST_ALERT_TIME", getString(R.string.db_app_id));
ed.apply(); // or commit()
I'm creating Shared Preferences as follows
preferences = getSharedPreferences("text", 0);
final Editor editor = preferences.edit();
String s1 = serverIP.getText().toString();
String s2 = serverPort.getText().toString();
String s3 = syncPass.getText().toString();
String s4 = proxyServer.getText().toString();
String s5 = proxyPort.getText().toString();
editor.putString("SERVERIP", s1);
editor.putString("SERVERPORT", s2);
editor.putString("SYNCPASS", s3);
editor.putString("PROXYSERVER", s3);
editor.putString("PROXYPORT", s3);
and onCreate I want to display the values in a new set of TextViews, but the first time I don't have any values stored in the shared preferences and will get a NULL Pointer exception.
I want to know if there is any built-in method which can check if the SharedPreferences contains any value or not, so that I can check if the key exists and if not, then replace the new set of TextViews with the preferences value.
Try contains(String key) Accorting to the Javadocs,
Checks whether the preferences contains a preference. Returns true if
the preference exists in the preferences, otherwise false.
Every method for fetching values from SharedPreferences has default value which is returned in case the key does not exist
preferences = getSharedPreferences("text", 0);
String value = preferences.getString("unknown_key",null);
if (value == null) {
// the key does not exist
} else {
// handle the value
}
Try out
SharedPreferences shf = getSharedPreferences("NAME_SharedPref", MODE_WORLD_READABLE);
String strPref = shf.getString("SERVERIP", null);
if(strPref != null) {
// do some thing
}
I know this is a late answer but for those who want to know if a shared preference is either empty or zero size, you can check it two ways.
preferences = getSharedPreferences("text", 0);
Map<String, ?> entries = preferences.getAll();//get all entries from shared preference
Set<String> keys = entries.keySet();//set all key entries into an array of string type
//first option
if(keys.isEmpty()){
//do your staff here
}
//second option
if(keys.size()==0){
//this shows that it is empty as well
//do your staff here
}
//Below is extra
//If you want to get the names of each keys also, you can use
//For each loop as well
//Go through the set of keys
for (String key : keys) {
String keyName = key;//get each key name
}
LoadRuns();
if (loadedruns == 1) {
Toast.makeText(MainActivity.this, "First run", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "No. runs: " + loadedruns,
Toast.LENGTH_SHORT).show();
}
loadedruns++;
SaveRuns("runs", loadedruns);
public void SaveRuns(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadRuns(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedruns = sharedPreferences.getInt("runs", 1);
}