SharedPreferences - Save number of button clicks - java

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();

Related

SharedPreferences in Android Studio Clicker App Not Working

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();
}
}

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, ""));

SecondActivity is not receiving the value - Intent related

import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
TextView t1,t2;
Button generate1;
MediaPlayer pickupgold, pickupplatinum;
SharedPreferences mySharedPreferences;
private static Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
pickupgold = MediaPlayer.create(this, R.raw.pickup_gold);
pickupplatinum = MediaPlayer.create(this, R.raw.pickup_platinum);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
OnClickButtonListener();
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
final ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
t1 = (TextView) findViewById(R.id.textView3);
t2 = (TextView) findViewById(R.id.textView8);
generate1 = (Button) findViewById(R.id.button);
generate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView userTextEntry = (TextView) findViewById(R.id.textView3);
String userData = userTextEntry.getText().toString();
int num2 = mySharedPreferences.getInt("INT_KEY1", Integer.parseInt(userData));
int num3 = mySharedPreferences.getInt("INT_KEY2", -1);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("parameter1", num2);
Random rand = new Random();
int num1 = rand.nextInt(100);
if (num1 % 2 == 0) {
pickupgold.start();
num2 += 1;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("INT_KEY1", num2);
editor.apply();
t1.setText(String.format("%d", num2));
imageView.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left));
Toast.makeText(getApplicationContext(), R.string.foundgold2, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), R.string.notfoundgold, Toast.LENGTH_LONG).show();
} if (num1 == 1){
pickupplatinum.start();
num3 += 1;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("INT_KEY2", num3);
editor.apply();
t2.setText(String.format("%d", num3));
imageView2.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left));
Toast.makeText(getApplicationContext(), R.string.foundplatinum1, Toast.LENGTH_LONG).show();
}
}
});
}
public void OnClickButtonListener() {
button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.example.tans.goldminer1.SecondActivity");
startActivity(intent);
}
}
);
}
This is MainActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
int goldamountval = intent.getIntExtra("parameter1", 0);
TextView goldamount = (TextView) findViewById(R.id.goldamount);
goldamount.setText("" + goldamountval);
}
and This is SecondActivity.java
I think the int value should be loaded from MainActivity.java but
When I go to SecondActivity, It does not seem to appear, Just showing 0.
What's the reason and how can i solve it? and Sorry, My Code may look like confused. :<
Try this on SecondActivity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("parameter1", num2);
startActivity(intent );
You need to start the SecondActivity after the first two lines :
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("parameter1", num2);
startActivity(intent);
Intent intent = new Intent(context, YourActivityClass.class);
intent.putExtra(KEY, );
startActivity(intent);
Seocnd Activity-
Intent intent = getIntent();
if (null != intent) {
String stringData= intent.getStringExtra(KEY);
int numberData = intent.getIntExtra(KEY, defaultValue);
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue);
}

End of counting - 'Click Counter'

I'm working on simple 'Click Countdown' application, which basically has an imagebutton function, which when pressed, displays the number of clicks from 10 to 9, 8, 7,... to 0. I have an issue finding how to change an imagebutton and stop counting when number of cliks will be 0.
This is the code I have so far:
package com.example.testapp;
import com.example.testapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
ImageButton button1;
TextView textView1;
int counter = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton imageButton;
imageButton = (ImageButton) findViewById(R.id.button1);
textView1 = (TextView) findViewById(R.id.textView1);
imageButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
counter--;
textView1.setText(""+ counter);
}
});
}
}
Change your ClickListener to the following:
public void onClick(View v) {
if (counter >= 0) {
counter--;
textView1.setText("" + counter);
} else if (counter == 0){
button1.setImageResource(R.id.yourdrawable);
counter--;
}
}
Also make sure to actually set button1:
button1 = (ImageButton) findViewById(R.id.button1);
You need to check the value of counter for the zero condition. For example, inside your onClick method:
if (counter == 0) {
//do something else, or do nothing
} else {
counter--;
textView1.setText(""+counter);
}

Categories

Resources