SharedPreferences in Android Studio Clicker App Not Working - java

I am creating a simple clicker program. I am clicking a pear picture and then it increments by 1 and displays that. I want to save this number so I they can click and then completely exit the app and when they return the same number they left off at is still there. This is my code but yet it still does not save that pears int when I restart the app.
CODE:
package pearclicker.pearclicker;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ImageButton imageButtonPear;
TextView showValue;
int pears;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showValue = (TextView) findViewById(R.id.countText);
}
public void PearIncrease(View v) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("PearCount", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("pearCount", pears);
pears++;
if (pears == 1) {
showValue.setText(pears + " pear");
editor.putInt("pearCount", pears);
editor.apply();
}
else {
showValue.setText(pears + " pears");
editor.putInt("pearCount", pears);
editor.apply();
}
}
}

Your code is doing fine when clicking the button to increase the value of your pear. but you're doing nothing in your onCreate() so you think that the SharedPreference is not storing the value of pear when you restart the app..
to do that you need some modification to your code.
public class MainActivity extends AppCompatActivity {
ImageButton imageButtonPear;
TextView showValue;
int pears = 0;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getApplicationContext().getSharedPreferences("PearCount", MODE_PRIVATE);
showValue = (TextView) findViewById(R.id.countText);
pears = pref.getInt("pearCount", 0); // This will get the value of your pearCount, It will return Zero if its empty or null.
showValue.setText(pears + " pears");
}
public void PearIncrease(View v) {
editor = pref.edit();
pears++;
showValue.setText(pears + " pears");
editor.putInt("pearCount", pears);
editor.apply();
}
}

Related

How to save the state of a radio group?

I want the user to have the same radio button checked which he had
previously checked before the app was closed.
This is my source code
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.R;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
textView = findViewById(R.id.text_view_selected);
Button buttonApply = findViewById(R.id.button_apply);
buttonApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
textView.setText("Your choice: " + radioButton.getText());
}
});
}
public void checkButton(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
Toast.makeText(this, "Selected Radio Button: " + radioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
I want the radio button states to be saved for next time the app is
used.
You should take a look at sharedPreferences : https://developer.android.com/training/data-storage/shared-preferences
Save your data :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("myRadio", radioButton.getText());
editor.commit();
Retrieve data :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String defaultValue = "";
String radioButtonText = sharedPref.getString("myRadio", defaultValue);
For now, you can do this :
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
TextView textView;
// Declare SharedPreferences as attributes
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
textView = findViewById(R.id.text_view_selected);
// Retrieve SharedPreferences
sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPref.edit();
Button buttonApply = findViewById(R.id.button_apply);
buttonApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
textView.setText("Your choice: " + radioButton.getText());
}
});
}
#Override
protected void onResume() {
int radioIdChecked = -1;
radioIdChecked = sharedPref.getInt("myRadioChecked", radioIdChecked);
if (radioIdChecked == -1) {
// ERROR, don't check anything
Log.d("TAG", "error: don't check anything");
}
else {
RadioButton radioButton = radioGroup.findViewById(radioIdChecked);
if (radioButton != null) {
radioButton.setChecked(true);
}
}
}
#Override
protected void onPause() {
editor.putInt("myRadioChecked", radioGroup.getCheckedRadioButtonId());
editor.commit();
}
Best

Save text/string internally Android [duplicate]

This question already has answers here:
Read/Write String from/to a File in Android
(11 answers)
Closed 4 years ago.
In this app, I want to save the text that ends up on the TextView view and be able to see it the next time I launch the app. I'm relatively new to Android Studio. How can I do this?
My code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button submit;
EditText habbit;
EditText money;
TextView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.button2);
habbit = (EditText) findViewById(R.id.habbit1);
money = (EditText)findViewById(R.id.money1);
view = (TextView)findViewById(R.id.textView3);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view.setText((habbit.getText().toString() + " for $" + money.getText().toString()) + "/day");
}
});
}}
You can use shared preferences to save the text in a file. And when app is open again you can retrieve the text from file and put in a textView.
public class MainActivity extends AppCompatActivity {
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences=getSharedPreferences("File_name",MODE_PRIVATE);
editor=preferences.edit();
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view.setText((habbit.getText().toString() + " for $" + money.getText().toString()) + "/day");
editor.putString("key",habbit.getText().toString());
editor.commit();
}
});
}
And then you can retrieve data as -
public class MainActivity extends AppCompatActivity {
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences=getSharedPreferences("File_name",MODE_PRIVATE);
String data = preferences.getString("key", "");
view = (TextView)findViewById(R.id.textView3);
view.setText(data);
}
}
You can use shared preferences to store a simple string.
static final String MY_PREF = "MY_PREF";
static final String SAVE_TEXT = "SAVE_TEXT";
SharedPreferences sharedPreferences = context.getSharedPreferences(MY_PREF, Context.MODE_PRIVATE);
//To store string use this line
sharedPreferences.edit().putString(SAVE_TEXT, textview.getText().toString()).commit();
//To retrieve the same use this line
sharedPreferences.getString(SAVE_TEXT, "default_value");

Having trouble in Session management

i m working on an application and i want to make user login only when he/she logouts his previous session but i m unable to do it. whenever i close my program and re-open it. it directs to Homepage again even if i had'nt logout. plz
package in.co.medimap.www.medimap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static in.co.medimap.www.medimap.R.layout.login;
/**
* Created by sony on 28-04-2016.
*/
public class login extends Activity {
TextView signup_text;
Button login_button;
EditText PHONE_NO,PASSWORD;
AlertDialog.Builder builder;
public static final String MyPREFERENCE ="Myprefs";
public static final String PHONE="phone";
public static final String PASS="password";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
signup_text=(TextView)findViewById(R.id.sign_up);
signup_text.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent(login.this,register.class));
}
});
PHONE_NO=(EditText)findViewById(R.id.phone_no);
PASSWORD=(EditText)findViewById(R.id.password);
login_button=(Button)findViewById(R.id.login_button);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ph = PHONE_NO.getText().toString();
String p=PASSWORD.getText().toString();
if (ph.equals("")||p.equals("")) {
builder = new AlertDialog.Builder(login.this);
builder.setTitle("Something went wrong...");
builder.setMessage("Please fill all the fields...");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
else
{
//see from here
sharedPreferences = getSharedPreferences(MyPREFERENCE,Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PHONE, ph);
editor.putString(PASS, p);
editor.commit();
BackgroundTask backgroundTask = new BackgroundTask(login.this);
backgroundTask.execute("login",ph,p);
}
}
});
}
}
this is my homeactivity where after logging user goes
and i want that if i hadn't logout then whenever i open my app it should start from here
package in.co.medimap.www.medimap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HomeActivity extends Activity {
Button Logout = null;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Logout = (Button) findViewById(R.id.Logout);
textView = (TextView) findViewById(R.id.welcome_txt);
String message = getIntent().getStringExtra("message");
textView.setText(message);
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
Intent intent = new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
}
If you want logout to happen each time user leaves the application, why don't you just do it manually?
you've already set Logout buttons setOnClickListener so just do this:
#Override
protected void onPause() {
super.onPause();
if(Logout != null) {
Logout.callOnClick();
}
}
This means every time user leaves this activity it will logout.
make sure you handle cases where if they leave activity but go to a different activity on your page, it doesn't log out.
=========== EDIT ===========
I'm guessing your login activity is the main activity that starts when application opens so just put this in onCreate before you perform any other tasks. right after setContentView, you should do this.
SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
String phone = sharedPreferences.getString(PHONE, "");
String pass = sharedPreferences.getString(PASS, "");
if(!phone.isEmpty() && !pass.isEmpty()) {
// this means ID and passwords are already saved so just start your home activity here
startActivity(new Intent(context, MainActivity.class));
finish();
}
In your MainActivity:
Just read the values from SharedPreferences and login if you have to.
Hope this helps.
========== EDIT 2
Also, your Logout should look like this. Don't use commmit or clear. put empty values and use apply
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PHONE, "");
editor.putString(PASS, "");
editor.apply();
Intent intent = new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
}
});

Android Edittext Sharedpreferences

Can someone please help me edit the following code so that it saves the info typed into the edittext and then once the app is relaunched it will automatically display the text that was saved in the edittext field. I have tried SharedPreferences tutorials but so far I have not been able to get it working.
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText txtLink;
Button btnOpenLink;
String defaultLink;
String secondLink;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
defaultLink = "http://";
secondLink = ".whatver.com";
txtLink = (EditText) findViewById(R.id.editText);
btnOpenLink = (Button) findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
btnOpenLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String server = txtLink.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, server);
editor.commit();
if(!TextUtils.isEmpty(server)){
Intent intent=new Intent(MainActivity.this,webactivity.class);
intent.setData(Uri.parse(defaultLink+server+secondLink));
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Please enter your server name.", Toast.LENGTH_LONG).show();
}
}
});
}
}
Verify the stored preferences and load them if any avaliable, after that display them in the textview
Example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
defaultLink = "http://";
secondLink = ".whatver.com";
txtLink = (EditText) findViewById(R.id.editText);
btnOpenLink = (Button) findViewById(R.id.button);
checkIfPreferencesAvaliable();
if(defaultLink!=null && secondLink!=null){
txtLink.setText(defaultLink+secondLink);
}
defaultLink = "http://";
secondLink = ".whatver.com";
void checkIfPreferencesAvaliable(){
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
defaultLink = preferences.getStr("mydefaultLink", null);
secondLink = preferences.getStr("mysecondLink", null);
}
In your onCreate(), check if you have already have values in your preferences-
String savedVal = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE).getString(Name, null);
if(savedVal == null){ //This means you don't have the saved values in your prefs file
//Do whatever you want to
} else{
//Use "savedVal" anyway you want
}
I fixed it by calling this
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
txtLink.setText(sharedpreferences.getString(Name, ""));

SharedPreferences - Save number of button clicks

I'm working on a simple 'Click Countdown' application, which basically has an imagebutton
function. When pressed it displays the number of clicks from 10 to 9, 8, 7,... to 0.
I have a problem, when I close the application the number of clicks starts again from
10. I wrote somethink, but it doesn´t work and say: Cannot refer to a non-final variable prefsEditor inside an inner class defined in a different method.-(prefsEditor) Can someone help me please?
This is the code I have so far. I there mistake?
package com.example.testapp;
import com.example.testapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageButton;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.google.ads.AdRequest;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.google.ads.AdView;
public class MainActivity extends Activity {
ImageButton button1;
TextView textView1;
int counter = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefsEditor = prefs.edit();
ImageButton imageButton;
imageButton = (ImageButton) findViewById(R.id.button1);
textView1 = (TextView) findViewById(R.id.textView1);
button1 = (ImageButton) findViewById(R.id.button1);
imageButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
if (counter >= 1) {
counter--;
textView1.setText("" + counter);
prefsEditor.putInt("counter", counter);
prefsEditor.commit();
} else if (counter == 0){
button1.setImageResource(R.drawable.image2);
counter--;
prefsEditor.putInt("counter", counter);
prefsEditor.commit();
}
}
});
}
}
make prefsEditor final
final SharedPreferences.Editor prefsEditor = prefs.edit();

Categories

Resources