Solution 1 :
Try initializing it like this
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Solution 2 :
it is solved like this…
String currentDate= DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(calendar.getTime());
SharedPreferences mydate = this.getSharedPreferences("mydata", Context.MODE_PRIVATE);
string1 = mydate.getString("stored", String.valueOf(DEFAULT_KEYS_DISABLE));
maxided = mydate.getInt("number", DEFAULT_KEYS_DISABLE);
if(!currentDate.equals(string1) || maxided == 0) {
string1 = currentDate;
mydate = getSharedPreferences("mydata", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mydate.edit();
editor.putString("stored", string1);
maxided=+1;
editor.putInt("number",maxided);
editor.apply();
}else{
Toast.makeText(this, "SharedPreference worked", Toast.LENGTH_SHORT).show();
}
refer= FirebaseDatabase.getInstance().getReference().child("daily").child(String.valueOf(maxided));
refer.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String mypic = snapshot.child("pic").getValue().toString();
Picasso.get().load(mypic).into(image1);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
Problem :
i used the sharedpreferences to store the value for the next time to be compared but it crashes. i supposed to create the code for the subject that “the image portion changes each day when the date changes” this is my logic. but i can’t make it practical in coding in android studio.
Calendar calendar = Calendar.getInstance();
String currentDate= DateFormat.getDateInstance(DateFormat.DATE_FIELD).format(calendar.getTime());
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if(string1 == null){
string1=currentDate;
}
string1 = savedInstanceState.getString("store_data");
if(currentDate != string1)
{
string1 = currentDate;
editor.putString("store_date", string1);
editor.apply();
Log.d("jomson","hello"+string1);
maxided = savedInstanceState.getInt("store_number");
refer=FirebaseDatabase.getInstance().getReference().child("daily").child(String.valueOf(maxided));
refer.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String mypic = snapshot.child("pic").getValue().toString();
Picasso.get().load(mypic).into(image1);
editor.putString("store_number", String.valueOf(maxided+1));
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}else{
}
}
Comments
Comment posted by Laurentiu Daniel
Add the logs when it crashes.
Comment posted by Random weins
i tried but is it correct sir?
Comment posted by Alex Mamo
If the app crashes, there is a stack trace. Please look that up on logcat, and add it to your question.