For the life of me I cannot figure out why I can’t get this method to enter the if statement.
protected void foo() {
Date d = new Date();
long now = d.getTime();
long start;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
start = settings.getLong(FIRST_USE_DATE, 0);
Log.w(this.getClass().getName(), Long.toString(start));
if (start == 0) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
}
return true;
}
Note that the log and debug mode shows that “start = 0”
I also tried
if (start == 0l) {
if (start == 0L) {
What the heck am I missing here? Does 0 != 0?
I’m developing in Eclipse with Java for Android. Thanks.
Edits:
#methodin - no sorry, that does not work.
#Aioobe - I have a breakpoint under the IF statement, that never gets made.
Edit2: Here is the actual code I'm running since you've asked.
protected boolean isDemoExpired() {
Date d = new Date();
long now = d.getTime();
long demoStart;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
demoStart = settings.getLong(FIRST_USE_DATE, 0);
if (demoStart == 0) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
System.out.println(Long.toString(demoStart));
return false;
}
return true;
}
I think your problem is exactly the opposite.
I've just debugged your code and it works, the problem is that the if statement it's always true because there's no editor.commit() after making the changes to the FIRST_USE_DATE variable.
protected void foo() {
Date d = new Date();
long now = d.getTime();
long start;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
start = settings.getLong(FIRST_USE_DATE, 0);
Log.w(this.getClass().getName(), Long.toString(start));
if (start == 0) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
***editor.commit();***
}
}
Edit: I've just tried debugging your actual code and the same thing happened: the if statement it's always true and it gets made every time because there's no editor.commit() to save the changes to the FIRST_USE_DATE variable.
protected boolean isDemoExpired() {
Date d = new Date();
long now = d.getTime();
long demoStart;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
demoStart = settings.getLong(FIRST_USE_DATE, 0);
if (demoStart == 0) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
****editor.commit();****
System.out.println(Long.toString(demoStart));
return false;
}
return true;
}
Why won't you use Long start instead of long and check for null value?
protected void foo() {
Date d = new Date();
long now = d.getTime();
Long start;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
start = settings.getLong(FIRST_USE_DATE, 0);
Log.w(this.getClass().getName(), Long.toString(start));
if (start == null) {
SharedPreferences.Editor editor = settings.edit();
editor.putLong(FIRST_USE_DATE, now);
}
}
it seems that auto-unboxing is happening here and you get zero value. Another question is why 0 == 0 check doesn't pass.
You are making a mistake somewhere...
Are you sure you are not entering the if statement AND that start = 0 ?
Are you showing us the code you are running ?
You could execute following code (equivalent to your code)
public static void main(String[] args) {
long start = 0;
if (start == 0) {
System.out.println(Long.toString(start));
}
}
And you'd see you enter the if statement...
Are you familiar with the concepts of hiding and shadowing? Do you have any other variables using the same names in this class or one of its parents?
I don't think there is anything wrong with your code - try rebooting your computer (its a Microsoft OS right? :)
If that don't work delete the offending code (end up with an empty method) compile and test to ensure there are no bugs. Then hardcode an acceptable value and test again. Finally retype your code - do not paste a copy.
Once, a very long time ago, I had something similar and it did not go away until I re-entered the code - my best guess is some hidden character was causing problems, but I have never seen it again (nor am I certain what the hell happened that time either).
Related
I want to get values from an array every day, respectively, and set these values to a textbox. I can get values from array and set them in textbox but next day value stays same. does not set the next value in array? what can I do?
<string-array name="morning">
<item>Good Morning. Message 1.</item>
<item>Good Morning. Message 2.</item>
<item>Good Morning. Message 3.</item>
</string-array>
mTestArray = getResources().getStringArray(R.array.morning);
preference_shared = this.getSharedPreferences("PREFERENCE", MODE_PRIVATE);
text_shared = this.getSharedPreferences("TEXT", MODE_PRIVATE);
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.DAY_OF_YEAR);
if (timeOfDay >= 0 && timeOfDay < 24) {
if (preference_shared.getBoolean("isFirstRun", true)) {
dailyGreetings.setText(mTestArray[(0) % (mTestArray.length)]);
saveDate();
}else {
if (!Objects.equals(preference_shared.getString("Date", ""), dateFormat.format(date))) {
int idx = new Random().nextInt(mTestArray.length);
dailyGreetings.setText(mTestArray[idx]);
text_shared.edit().putString("TEXT", dailyGreetings.getText().toString()).apply();
saveDate();
}
else {
dailyGreetings.setText(text_shared.getString("TEXT", ""));
}
}
}
It's Easy just
Resources res = getResources();
String[] mornings = res.getStringArray(R.array.morning);
//then use mornings as you use array.
String morning[] = getResources().getStringArray(R.array.morning);
// Solution
SharedPreferences sharedPreferences = getSharedPreferences("my_preference", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String currentDate = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault()).format(System.currentTimeMillis());
String[] msgArrays = getResources().getStringArray(R.array.morning);
String savedDate = sharedPreferences.getString(DATE_KEY, "");
int savedCounter = sharedPreferences.getInt(COUNTER_KEY, 0);
// First time
if (savedDate.isEmpty()) {
editor.putInt(COUNTER_KEY, savedCounter);
editor.putString(DATE_KEY, currentDate);
editor.apply();
} else if (!savedDate.equals(currentDate)) {
// New date appears, update shared preference.
savedCounter++;
if (savedCounter < msgArrays.length) {
editor.putInt(COUNTER_KEY, savedCounter);
editor.putString(DATE_KEY, currentDate);
editor.apply();
}
}
binding.tvTitle.setText(msgArrays[savedCounter]);
In this snipped of code, I'm updating shared preference by date and counter.
Date: It will be saved for next date, and if these both are not matching, shared preference will gets update with counter.
Counter: The position of your strings-arrays.
Reset: I have add another check that if in case your counter reaches to the end of array, it will be reset to '0'.
I wish to ask some question at Java. I have list of time (String) which i parsed from JSON data. I need to find which time is closer to system time. Its like this, now time is 16:40. And my time list contains
"16:32", "16:38", "16:44", "16:50" and so on. For 16:40, 16:38 is closer than 16:44 and i need to find this. I've tried to get current index and next index, parse them and initate new Calender and so on. But i cant figure out how can i do next.
Any solutions for this problem?
String returnTime = current.getDonus();
if (i < list.size() + 1) {
TimeList nextOne=list.get(i+1);
String nextReturnTime = nextOne.getDonus();
String[] parsedNextReturn = nextReturnTime.split(":");
String[] parsedReturn = returnTime.split(":");
Date date = new Date();
Calendar calNextReturn= Calendar.getInstance();
calNextReturn.setTime(date);
calNextReturn.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parsedNextReturn[0]));
calNextReturn.set(Calendar.MINUTE, Integer.parseInt(parsedNextReturn[1]));
calNextReturn.set(Calendar.SECOND, 0);
calNextReturn.set(Calendar.MILLISECOND, 0);
Calendar calCurrentReturn= Calendar.getInstance();
calCurrentReturn.setTime(date);
calCurrentReturn.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parsedReturn[0]));
calCurrentReturn.set(Calendar.MINUTE, Integer.parseInt(parsedReturn[1]));
calCurrentReturn.set(Calendar.SECOND, 0);
calCurrentReturn.set(Calendar.MILLISECOND, 0);
Calendar calSystem = Calendar.getInstance();
calSystem.setTime(date);
calSystem.set(Calendar.SECOND, 0);
calSystem.set(Calendar.MILLISECOND, 0);
}
Try this:
long smallestABS = Long.MAX_VALUE;
long systemTime = System.currentTimeMillis();
long timeClosest;
for (long time : timeList) {
long abs = Math.abs(systemTime - time);
if(smallestABS > abs){
smallestABS = abs;
timeClosest = time;
}
}
I'm storing an ArrayList and Int in Shared Preference, and in fragment i call storage.arraylist().get(storage.int()); to get the position in array but every activity get the right position except the fragment its get the wrong position
My goal is to make the fragment get the right position the int that is stored but he gets the backward of this int, if the int is 15 and the arraylist.size is 16 the fragment gets 14 but in any activity the get 15 position, i tried in fragment to just put in this int + 1 to get the right but the surprise he gets an error because the int it equal to the arraylist.size
Here Where i add an item to the arraylist
storage.storeAudio(CardList.get(position));
if(!app.ismServiceBound()) {
fragment.setSlide_up();
}
app.PlayerBroadCast(1);
fragment.Start();
The storeAudio Method
public void storeAudio(ModelCardView model) {
preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
if (loadAudio() != null) {
arrayList = loadAudio();
}
arrayList.add(model);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString("audioArrayList", json);
editor.apply();
}
The execution of the BroadCast in the first code
//Load data from SharedPreferences
audioList = storage.loadAudio();
audioIndex = audioList.size();
audioIndex--;
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
storage.storeAudioIndex(audioIndex);
} else {
stopSelf();
}
In the end the fragment start to get the arraylist and the int to display some info
public void Start(){
if(!app.ismServiceBound()) {
view.setVisibility(View.GONE);
}else if (app.ismServiceBound() && storage.getState()) {
start.setImageResource(R.drawable.play);
view.setVisibility(View.VISIBLE);
}else if(app.ismServiceBound() && !storage.getState()){
start.setImageResource(R.drawable.pause);
view.setVisibility(View.VISIBLE);
}
songName.setText(storage.loadAudio().get(storage.loadAudioIndex()).getId());
bandName.setText(storage.loadAudio().get(storage.loadAudioIndex()).getSinger());
}
but its gets the wrong position i try to use the same code in activity and its work perfect without any problem but i don't know why in this fragment gets a wrong position, and Thanks for helping me.
I want my app to check some web page only once a day, so I want the data to be saved anded reloaded upon starting the app again.
I followed this tutorial, but I can not save the result with MainActivity extends AppCompatActivity:
String url = "https://en.wikipedia.org/wiki/Main_Page";
SharedPreferences data;
SharedPreferences.Editor dataEditor;
String sDate = date.getString("date", "");
DateFormat df = new SimpleDateFormat("MMMM d");
String date = df.format(Calendar.getInstance().getTime());
if(sDate != date){ // <-- this does not work
new Date().execute();
}
and Date extends AsyncTask<Void, Void, Void>:
Document document = Jsoup.connect(url).get();
Elements date = document.select("div#mp-otd p b");
String sDate = date.getText();
dataEtitor.setString("date", sDate)
dataEtitor.commit;
The "Date extends AyncTask" class always start.
editor.commit() is used in order to save changes to shared preferences.
Add below line of code after setString
dataEtitor.commit(); // commit changes
SharedPreferences Example as follow
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing or Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes
You muss use !(sDate.equals(date) in place of sDate != date, because the Strings are new and so they can not be compare each other.
Here is the code where I put the values:
if(soundima == 1){
soundima=0;
editor.putInt("sOn", soundima);
editor.commit();
}
else if(soundima == 0){
soundima=1;
editor.putInt("sOn", soundima);
editor.commit();
}
Then when I quit the application, the values are not remembered. I get the values with this code:
editor = PreferenceManager.getDefaultSharedPreferences(this);
soundima = editor.getInt("sOn", 0);
I am not entirely sure why that is not working. However, the following code should solve the problem.
//create a constant to use for the shared preferences
public static final String YOUR_CONSTANT = "Preferences";
Then to place the values in shared preferences, use the following code:
if(soundima == 1){
soundima = 0;
SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0);
SharedPreferences.Editor editor = sound.edit();
editor.putInt("sOn", soundima);
editor.commit();
}
else if(soundima == 0){
soundima = 1;
SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0);
SharedPreferences.Editor editor = sound.edit();
editor.putInt("sOn", soundima);
editor.commit();
}
Then to retrieve the values, use this code:
SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0);
soundima = sound.getInt("sOn", 0);