App crashes when using Shared Preferences - java

Im making a simple app, which counts the clicks of a button and saves the integer with a Shared Preferences. I tried it with the following code, but the app crashes all the time, if I try to open "Singleplayer"
public class Singleplayer extends AppCompatActivity {
private int sp1;
private int record;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleplayer);
final Button button1 = (Button) findViewById(R.id.buttonspieler1);
final TextView lbl1 = (TextView)findViewById(R.id.lblspieler1);
final TextView lbl2 = (TextView)findViewById(R.id.lblrekord);
SharedPreferences data_record = getSharedPreferences("savegame", 0);
record = data_record.getInt("myKey1", 0);
lbl2.setText(String.valueOf(record));
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
}
});
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
}

you are using sharedPrefrence in your onStop() so you will face many issue here, i suggest to use it at the end of click method
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
});
so why the app crash, because the sharedPref dosen't carry any value it's null
please check this

Related

How to store a count given by a user and the user's choices across activities in Android Studio

I want to make a basic app in which I offer the user to add a trackers of various things like water etc. and then he can store how many glasses he has drank so far. However I want it to have saved the information even after the app closes. Please provide a solution.
This is what I've tried so far:-
public class MainActivity extends AppCompatActivity {
Button btnAddTracker;
//public static final String MY_PREFS_NAME = "MyCounter";
ImageView ivWater;
TextView tvWaterCount;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = PreferenceManager.getDefaultSharedPreferences(this);
editor = pref.edit();
if(pref.getBoolean("WaterStatus",false)){
ivWater.setVisibility(View.VISIBLE);
tvWaterCount.setVisibility(View.VISIBLE);
tvWaterCount.setText(pref.getInt("waterCount",0));
}
btnAddTracker=findViewById(R.id.btnAddTracker);
ivWater=findViewById(R.id.ivWater);
tvWaterCount=findViewById(R.id.tvWaterCount);
btnAddTracker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,TrackerListActivity.class);
startActivity(intent);
}
});
editor.putInt("waterCount", 8);
editor.apply();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
if(pref.getBoolean("WaterStatus",false)){
ivWater.setVisibility(View.VISIBLE);
tvWaterCount.setVisibility(View.VISIBLE);
tvWaterCount.setText(pref.getInt("waterCount",0));
}
}
}
}
public class TrackerListActivity extends AppCompatActivity {
Button btnAddWaterTracker;
ImageView ivReturn,ivWater;
TextView tvWaterStatus;
boolean WaterStatus;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracker_list);
ivReturn=findViewById(R.id.ivReturn);
btnAddWaterTracker=findViewById(R.id.btnAddWaterTracker);
ivWater=findViewById(R.id.ivWater);
tvWaterStatus=findViewById(R.id.tvWaterStatus);
pref = PreferenceManager.getDefaultSharedPreferences(this);
editor = pref.edit();
WaterStatus=pref.getBoolean("waterStatus",false);
ivReturn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent2=new Intent();
intent2.putExtra("waterStatus",WaterStatus);
setResult(RESULT_OK,intent2);
if(btnAddWaterTracker.getVisibility()==View.GONE) {
editor.putBoolean("waterStatus",true);
editor.apply();
}
TrackerListActivity.this.finish();
//Intent intent1=new Intent(TrackerListActivity.this,MainActivity.class);
//startActivity(intent1);
}
});
btnAddWaterTracker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WaterStatus=true;
btnAddWaterTracker.setVisibility(View.GONE);
tvWaterStatus.setVisibility(View.VISIBLE);
//editor.putBoolean("waterStatus",true);
//editor.apply();
}
});
}
}
There are many ways of saving informations locally, you could save it on a file using the Json or XML format, you could also use SQLite which are supported by all recent smartphones.
Unfortunately you won't get anyone to code for you on this website, check this link

Android CheckBox OnCheckListener doesn't work

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
editText.setText(nm);
editText1.setText(ps);
Toast.makeText(Page1.this,"Checkbox Remember me is " + String.valueOf(b),Toast.LENGTH_LONG).show();
}
}
});
I am trying to make a login page which has two EditTexts and a CheckBox. I am trying to save login details in sharedprefrences when the CheckBox is checked. In my code, I set the OnCheckedListner to know whether it is checked or not. But the boolean value b is always true...WHY?
Please Help me!
Full Code on Page1 activity :
public class Page1 extends AppCompatActivity {
Button button;
EditText editText,editText1;
CheckBox checkBox;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
button = (Button)findViewById(R.id.bt1);
editText = (EditText)findViewById(R.id.et1);
editText1 = (EditText)findViewById(R.id.et2);
checkBox = (CheckBox)findViewById(R.id.cb1);
sharedPreferences = getSharedPreferences("MYSP", MODE_PRIVATE);
final String nm = sharedPreferences.getString("uname", "");
final String ps = sharedPreferences.getString("upass", "");
final boolean saveLogin = sharedPreferences.getBoolean("save",false);
final boolean logout = sharedPreferences.getBoolean("logout", false);
if (!logout){
Intent intent = new Intent(Page1.this, ProfilePage.class);
startActivity(intent);
}
final boolean[] isChecked = new boolean[1];
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
editText.setText(nm);
editText1.setText(ps);
Toast.makeText(Page1.this,"Checkbox Remember me is "+ String.valueOf(b) ,Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(Page1.this,"Checkbox Remember me is "+ String.valueOf(b),Toast.LENGTH_LONG).show();
}
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editText.getText().toString();
String pass = editText1.getText().toString();
SharedPreferences.Editor editor = sharedPreferences.edit();
if (isChecked[0]) {
editor.putString("uname", name);
editor.putString("upass", pass);
editor.putBoolean("save", true);
editor.putBoolean("logout", false);
editor.commit();
}
else {
editor.putString("uname", name);
editor.putString("upass", pass);
editor.putBoolean("logout", false);
editor.commit();
}
Intent intent = new Intent(Page1.this, ProfilePage.class);
startActivity(intent);
}
});
}
}
ProfilePage Activity code :
public class ProfilePage extends AppCompatActivity {
Button button;
TextView textView;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_page);
button = (Button)findViewById(R.id.btn1);
textView = (TextView)findViewById(R.id.tv1);
sharedPreferences = getSharedPreferences("MYSP", MODE_PRIVATE);
final String n = sharedPreferences.getString("uname", "");
final String p = sharedPreferences.getString("upass", "");
textView.setText("Welcome "+ n + " ");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = sharedPreferences.edit();
if (sharedPreferences.getBoolean("save", false)) {
editor.putString("uname", n);
editor.putString("upass", p);
editor.putBoolean("logout", true);
editor.commit();
}
else {
editor.clear();
editor.putBoolean("logout", true);
editor.commit();
}
textView.setText("Logout Success!");
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
}
Your code handles only the case b = true. Modify your code to include an else part like
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
editText.setText(nm);
editText1.setText(ps);
Toast.makeText(Page1.this,"Checkbox Remember me is true",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Page1.this,"Checkbox Remember me is false",Toast.LENGTH_LONG).show();
}
}
});
This is your checkbox in xml:
<CheckBox
android:id="#+id/remember_me_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#color/white"
android:gravity="left" />
This is your java code:
private CheckBox remember_me_checkbox;
private boolean isRemembered; //false by default
remember_me_checkbox = (CheckBox) findViewById(R.id.remember_me_checkbox);
remember_me_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isRemembered = isChecked;
}
});
Whenever user successfully logged in, you just save it in the preference. At the same time you have to save username and password as per your requirement.
SharedPreferences pref
=getApplicationContext().getSharedPreferences(AppPreferences.PREF_FIREBASE_TOKEN, 0);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("remembered", isRemembered);
editor.commit();
And, next time when you come to this screen in case of logout. You will check whether isRemembered is true or not, if it is true then you get the username and password and set them to respective editTexts.
SharedPreferences pref = getApplicationContext().getSharedPreferences(AppPreferences.PREF_FIREBASE_TOKEN, 0);
boolean remembered = pref.getBoolean("remembered", false);
if(remembered ){
//get the username and password from pereference and set to editTexts.
}
You shouldn't have added OnCheckChangeListener in first place. You should have saved the credentials in SharedPreference when Login button is clicked by checking all the validation of email and password and checked status of your remember me checkbox.
Also in onCreate you must checked for isRemember value from SharedPreference and show put the values in Edittext accordingly.

Save value of Int (Shared Preference)

I'm new to java. I've made a counter which goes up as user holds on a button. I want the app to start with int value of where it left. I know SharedPreference is the way to go but I've no idea how to use it. I'm not sure where to put which part of SharedPreference. Thank you.
public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
text.setText(String.valueOf(count));
return false;
}
});
}
}
Add the following function to your activity
public int getValue(String key) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int value = sharedPref.getInt(key, 0);
return value;
}
public void saveValue(String key, int value) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.commit();
}
Some code added in your onCreate() method
final String key = "somekey";
count = getValue(key); //get value from sharedPreference
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
text.setText(String.valueOf(count)); // set it first
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
saveValue(key,count);
text.setText(String.valueOf(count));
return false;
}
});
You can do it like this,save count in SharedPreference when destroy the activity and read value from SharedPreference when you create it:
public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;
SharedPreferences sh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
sh = getSharedPreferences("sh_name", MODE_PRIVATE);
count = sh.getInt("count", 1);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
text.setText(String.valueOf(count));
return false;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
sh.edit().putInt("count", count).apply();
}
}
Try turning
int count = 1;
into
static int count = 1;
I'm also somewhat a Java noobie so this may or may not work.

how to retrive the value of shared preference for checking the condition

here I have three buttons Yes no maybe for three buttons I have changed the colour when the button clicked and store the value of clicked button in shared preference for hold the colour when ever I back to the button
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.invitation, null);
eventNameTxtV = (TextView) convertView.findViewById(R.id.invitation_title);
eventPlaceTxtV = (TextView) convertView.findViewById(R.id.invitation_place);
eventNameTxtV.setText(eventMOs.get(position).getText());
eventPlaceTxtV.setText(eventMOs.get(position).getPlace());
convertView.setTag(position);
View v = convertView.findViewById(R.id.invitation_single);
final Button yesBtn = (Button) convertView.findViewById(R.id.yesbutton);
final Button noBtn = (Button) convertView.findViewById(R.id.nobutton);
final Button maybeBtn = (Button) convertView.findViewById(R.id.buttonmaybe);
final LinearLayout eventLayout = (LinearLayout) convertView.findViewById(R.id.invitation_single);
final LinearLayout responseLayout = (LinearLayout) convertView.findViewById(R.id.hidden);
//Based on the user click, response will be stored
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// highlight the button when clicked
yesBtn.setBackgroundColor(Color.YELLOW);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks yes button in invitation response layout,response would be stored as 1 for event user
final int response = 1;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
//create shared preferences here
prefs =getActivity().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("buttonClicked","true");
editor.commit();
/*SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 1);
editor.commit();*/
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.YELLOW);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks no button in invitation response layout,response would be stored as 0 for event user
final int response = 0;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 0);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
maybeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.YELLOW);
responseLayout.setVisibility(View.GONE);
//If user clicks maybe button in invitation response layout,response would be stored as for event user
final int response = 2;
userMO.setIsAttending(response);
final long eventId = eventMOs.get(position).getEventId();
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn",2);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
here I have to hold the colour change of button whenever I return back to the app if I selected any of the button .so how to use and retrieve the shared preference value
this is the code for show the yes no maybe buttons together when I clicked the event
eventLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.invitation_single:
responseLayout.setVisibility(View.VISIBLE);
break;
}
}
});
SharedPreferences gives you the ability to store different kind of data, such as boolean or int.
To accomplish your task, you could store the color of each button in SharedPreferences; something like:
editor.putInt("button_one", R.color.buttone_one_selected);
Remember, when you'll retrieve that color, you have to resolve it with:
int buttonOneColor = sharedPrefs.getInt("button_one", default_value);
int colorBackground = getResources().getColor(buttonOneColor);
You can change color of your button using this...
In onCreate:
SharedPreferences prefs = getSharedPreferences("myPrefs",
Context.MODE_PRIVATE);
now check for the boolean value stored in the preferences :
boolean b1_pressed = prefs.getBoolean("button1_pressed",false);
if(b1_pressed){
//code to change color of button to pressed state
}
else{
//code to change color of button to normal state
}
Now in your button's onClick method:
if(b1_pressed){
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",false);
editor.commit();
}
else{
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",true);
editor.commit();
}

Sending text from intent to another intent

This is the write activity. In here I want to write a text and after clicking a button I want this text to appear in a new activity called read activity.
public class Write extends Activity implements OnClickListener
{
EditText text; TextView retrive1;
public static String filename="Mysharedstring" ;
SharedPreferences someData;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.write);
setupVariables();
someData = getSharedPreferences(filename, 0);
}
private void setupVariables()
{
Button sav= (Button) findViewById(R.id.save);
Button ret= (Button) findViewById(R.id.retrive);
text= (EditText) findViewById(R.id.txtText);
retrive1= (TextView) findViewById(R.id.textview);
ret.setOnClickListener(this);
sav.setOnClickListener(this);
}
public void onClick(View v)
{
String stringdata= text.getText().toString();
SharedPreferences.Editor editor = someData.edit();
editor.putString("sharedString", stringdata);
editor.commit();
}
}
I don't know what to write in the read activity.
public void onClick(View v)
{
//???
}
The most simple way that I can think of is this first Activity
Intent intent= new Intent(this, theOtherActivity.class);
intent.putExtra(Key, "Value");
startActivity(intent);
And on theOtherActivity
String receivedData=getIntent().getExtras().getKey(Key);
public void onClick(View v)
{
// get the shared string from the SharedPreference
SharedPreferences sp = getSharedPreferences("Mysharedstring",0);
String s = sp.getString("sharedString","Nothing found.");
// display the shared string
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
Sources for SharedPreferences:
How to save app settings?
How to keep information about an app in Android?
Shared Preferences | Android Developers

Categories

Resources