Clicker App: Saves Clicks not Correctly - android

I made a Clicker App (like cookie clicker). But when i Restart the App, the app saves the clicks, but only visible, so i mean when i click on the button, the clicks will be set to 0 again. So my question: Is my SharedPreference correct, or did i have done an mistake?
My complete MainActivity.java:
package com.rage.clicker;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View; import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import static com.rage.clicker.R.id.highscore_text;
import static com.rage.clicker.R.id.textView88;
public class MainActivity extends AppCompatActivity {
SoundPool mySound;
int playClick;
private final String TAG = this.getClass().getName();
ImageView hi;
TextView tv_clicks;
TextView ht;
ImageView b_click;
Button save;
int clicks;
SharedPreferences sf;
public static final String preference = "pref";
public static final String saveIt = "saveKey";
private TextView highScoreView;
private TextView currentScoreView;
private int currentScore;
private int highScore;
private String highScoreString;
private String currentScoreString;
private SharedPreferences msharedPreferences;
private static final String FILENAME = "PreferencesFilename";
private static final String VAL_KEY = "ValueKey";
private EditText editText;
private TextView TEV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Speichern laden
TEV = (TextView) findViewById(R.id.textView88);
SharedPreferences sharedPrefs = getSharedPreferences(FILENAME, 0);
TEV.setText(sharedPrefs.getString(VAL_KEY, ""));
//Speichern laden
msharedPreferences = getPreferences(MODE_PRIVATE);
mySound = new SoundPool(100, AudioManager.STREAM_MUSIC, 0);
playClick = mySound.load(this, R.raw.click, 1);
tv_clicks = (TextView) findViewById(textView88);
b_click = (ImageView) findViewById(R.id.imageView);
hi = (ImageView) findViewById(R.id.imageView);
b_click = (ImageView) findViewById(R.id.imageView);
ht = (TextView) findViewById(highscore_text);
final TextView TV = (TextView) findViewById(R.id.highscore_text);
currentScoreString = getString(R.string.current_score);
highScoreString = getString(R.string.high_score);
currentScore = clicks;
highScore = msharedPreferences.getInt(highScoreString, 0);
save = (Button) findViewById(R.id.button);
save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast dumplings= Toast.makeText(MainActivity.this, "Adolf4", Toast.LENGTH_LONG);
dumplings.show();
}
});
b_click.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final ImageView zoom = (ImageView) findViewById(R.id.imageView);
final Animation zoomAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.size);
zoom.startAnimation(zoomAnimation);
mySound.play(playClick, 1, 1, 1, 0, 1);
clicks++;
tv_clicks.setText("Klicks: " + clicks);
ht.setText(currentScoreString + ": Test" + currentScore);
}
});
}
protected void init() {
currentScoreView.setText(currentScoreString + ": asd" + currentScore);
highScoreView.setText(highScoreString + ":34 " + highScore);
}
#Override
protected void onStop() {
super.onStop();
//Speichern
SharedPreferences sharedPrefs = getSharedPreferences(FILENAME, 0);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(VAL_KEY, TEV.getText().toString());
editor.commit();
//Speichern
}
}

When you save data, you take click's count value from TEV TextView, but inside onClick event you update tv_clicks and TEV always remains zero by default. You should save clicks value like this
editor.putInt(VAL_KEY, clicks);
Then you should load clicks value and set it in the TextView:
clicks = sharedPrefs.getInt(VAL_KEY, 0)
TEV.setText(String.valueOf(clicks));

Related

Sharedprefrences not saving?

When i try to save a variable to shared preferences then call it in an editext it is not being saved? I've been looking around for hours but i cannot find anything on it. I know that sharedPrefrences acts like a dictionary in a way but other than that i don't understand why this is not working :(
package com.example.gatorblocks;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class block1Settings extends WearableActivity{
private TextView mTextView;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block1_settings);
configureBackButton();
configureColor();
Button addTextButton = (Button) findViewById(R.id.Apply);
TextView simpleEditText = findViewById(R.id.simpleEditText);
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("classes1","1-1")); //set textbox to equal current class
final EditText vEditText = (EditText) findViewById(R.id.simpleEditText);
mTextView = (TextView) findViewById(R.id.text);
// Enables Always-on
setAmbientEnabled();
addTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String enteredText = vEditText.getText().toString(); //sets the array value of block to the editText
test(enteredText);
}
});
}
private void configureColor() {
Button Block1 = (Button) findViewById(R.id.colorButton);
Block1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, colorBlock1.class));
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
}
private void configureBackButton(){
Button backbutton = (Button) findViewById(R.id.backButton);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, classes.class));
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
finish();
}
});
}
public void test(String enteredText){
SharedPreferences pref = getSharedPreferences("classes.txt", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("class1", enteredText);
editor.apply();
}
}
How did you get data from SharedPreferences which is not saved? You saved data using key class1 and want to get it by classes1 which is not correct way. You have to use same key. Try using
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("class1","1-1"));

Android: Settings "onResume"?

I'm working on a Android App and the layout and all the "android" specific stuff made a friend of my. I only was responsible for the "app" itself.
Nevertheless,
I would like to change some settings, e.g. change the server the stats produced by the app, should be transfered.
Here is the Settings.java:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
public class Settings extends Activity {
private Context mContext;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefEditor;
private EditText textName, textIP;
private RadioButton rdOnline, rdOffline;
private RadioGroup rdGroup;
private Button butSpeichern;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_settings);
mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
mPrefEditor = mPrefs.edit();
textName = (EditText) findViewById(R.id.txtBenutzer);
textIP = (EditText) findViewById(R.id.txtIP);
rdOffline = (RadioButton) findViewById(R.id.rdOffline);
rdOnline = (RadioButton) findViewById(R.id.rdOnline);
rdGroup = (RadioGroup) findViewById(R.id.radioDB);
butSpeichern = (Button) findViewById(R.id.btnSpeichern);
butSpeichern.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveSettings();
}
});
//Online default an
rdOnline.setChecked(true);
rdOffline.setChecked(false);
loadSettings();
//ggf. Lan
System.out.println("online");
if(automatischLAN()){
setLan();
}
}
private void saveSettings()
{
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.putString("benutzer", textName.getText().toString());
mPrefEditor.putString("ip", textIP.getText().toString());
mPrefEditor.apply();
finish();
}
private void loadSettings() {
textName.setText(mPrefs.getString("benutzer", ""));
textIP.setText(mPrefs.getString("ip", "192.168.0.50"));
rdOnline.setChecked(mPrefs.getBoolean("onlineDB", true));
rdOffline.setChecked(!mPrefs.getBoolean("onlineDB", true));
}
public boolean automatischLAN(){
Calendar cal = new GregorianCalendar();
Date currenttimen = new Date();
cal.setTime(currenttimen);
int freitag = cal.get(Calendar.DAY_OF_WEEK);
int STUNDE = 0;
STUNDE = cal.get(Calendar.HOUR_OF_DAY);
System.out.println(STUNDE);
if(freitag == Calendar.FRIDAY && STUNDE>11 && STUNDE< 14 ) {
System.out.println("lan");
return false;
}
else {
System.out.println("online");
return true;
}
}
public void onBackPressed()
{
saveSettings();
super.onBackPressed();
}
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
}
}
I'm afraid my setLan() method isn't working as the values are not stored in the prefs...
What is the easieast way to check prefs and chance them on each start of the app?
Thanks for your help
You have to commit the changes in the SharedPreference.Editor variable. Replace your function above with the given one
public void setLan(){
rdOnline.setChecked(false);
rdOffline.setChecked(true);
System.out.println("sollte lan sein");
mPrefEditor.putBoolean("onlineDB", rdOnline.isChecked());
mPrefEditor.apply();
}

TextView to display sharedpreference EditText

I'm trying to Save an editText to Sharedprefrences so that it displays in the TextView amnt. It's displaying it but not saving it? what am I doing wrong? I am new to this, just a little weekend hobby so I'm sorry if this is a stupid question, thanks for your time.
package org.iimed.www;
import java.util.Calendar;
import org.iimed.www.DateTimePicker.DateWatcher;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.inputmethodservice.Keyboard.Key;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class CaAdd extends Activity implements DateWatcher,OnClickListener{
Button button_click,amount;
int amountt = 0;
Key at;
EditText amountedit;
String amountText;
String amountString;
TextView dateResult, date2,amnt;
int hrs,min;
SharedPreferences.Editor editor ;
SharedPreferences prefs;
String amntprefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datetimeactivity);
dateResult = (TextView)findViewById(R.id.textview1);
date2 = (TextView)findViewById(R.id.textView2);
button_click = (Button)findViewById(R.id.setbtn);
button_click.setOnClickListener(this);
amnt = (TextView)findViewById(R.id.amountText);
}
public final String AT = "Amount";
public void loadDefaultSharedPreferences() {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs != null) {
String loadUsername= prefs.getString(
AT , null);
if (loadUsername != null && !loadUsername.isEmpty()) {
amnt.setText(loadUsername);
}}}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.setbtn:
final Dialog mDateTimeDialog = new Dialog(this);
// Inflate the root layout
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
mDateTimePicker.setDateChangedListener(this);
mDateTimePicker.initData();
amountedit = (EditText)mDateTimeDialogView.findViewById(R.id.amountedit);
ImageButton increase = (ImageButton)mDateTimeDialogView.findViewById(R.id.increase);
increase.setOnClickListener(new OnClickListener(){
public void onClick(View v){
amountt++;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
amnt.setText(amountText);
}
});
ImageButton decrease = (ImageButton)mDateTimeDialogView.findViewById(R.id.decrease);
decrease.setOnClickListener(new OnClickListener(){
public void onClick(View v){
amountt--;
amountText = Integer.toString(amountt);
amountedit.setHint(amountText);
amnt.setText(amountText);
}
});
Button setDateBtn = (Button)mDateTimeDialogView.findViewById(R.id.SetDateTime);
// Update demo TextViews when the "OK" button is clicked
setDateBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(CaAdd.this,AlarmReceiver.class);
PendingIntent pi=PendingIntent.getActivity(CaAdd.this, 2, intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alm=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
hrs=mDateTimePicker.getHour();
min=mDateTimePicker.getMinute();
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,hrs);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 0);
alm.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), pi);
mDateTimePicker.clearFocus();
String result_string = mDateTimePicker.getMonth() + "/" + String.valueOf(mDateTimePicker.getDay()) + "/" + String.valueOf(mDateTimePicker.getYear())
+ " " + String.valueOf(mDateTimePicker.getHour()) + ":" + String.valueOf(mDateTimePicker.getMinute());
if(mDateTimePicker.getHour() > 12) result_string = result_string + "PM";
else result_string = result_string + "AM";
date2.setText(result_string);
mDateTimeDialog.dismiss();
}
});
Button cancelBtn = (Button)mDateTimeDialogView.findViewById(R.id.CancelDialog);
// Cancel the dialog when the "Cancel" button is clicked
cancelBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.reset();
mDateTimeDialog.cancel();
}
});
// Reset Date and Time pickers when the "Reset" button is clicked
Button resetBtn = (Button)mDateTimeDialogView.findViewById(R.id.ResetDateTime);
resetBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.reset();
}
});
mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Set the dialog content view
mDateTimeDialog.setContentView(mDateTimeDialogView);
//Display the dialog
mDateTimeDialog.show();
}}
public void onDateChanged(Calendar c) {
Log.e("","" + c.get(Calendar.MONTH) + " " + c.get(Calendar.DAY_OF_MONTH)+ " " + c.get(Calendar.YEAR));
String result_string =String.valueOf(c.get(Calendar.MONTH)+1) + "/" + String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "/" + String.valueOf(c.get(Calendar.YEAR));
// _tvUserDOB.setTypeface(CGlobalVariables.tfFoEnglish);
dateResult.setText(result_string+" (mm/dd/yyyy)");
}
public void saveDefaultPreferences() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);{
SharedPreferences.Editor editor = prefs.edit();
final String AT = "Amount";
editor.putString(AT,amountText);
editor.commit();}
}}
Shared preferences allows you to save and retrieve key, value pair data.
Initialization:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
// 0 - for private mode
Editor editor = pref.edit();
Storing Data:
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
Retrieving Data:
pref.getString("key_name", null); // getting String
To know more about SharedPreferences or to try out a simple example, check this
You can only save key-value pairs for some of the primitives and String (String set also) only. Android views can never be saved anywhere.
SharedPreferences manager =PreferenceManager.getDefaultSharedPreferences(context);
Use it for saving and retrieving data as follows
// for saving data
manager.edit().putString(context.getString(AT), YOUR_TEXT).commit()
// for retrieving data
manager.getString(context.getString(AT), "");

Error: Final local variable score cannot be assigned, since it is defined in an enclosing type?

I am trying to use the getIntent value(score) which is retrieve from the previous activity but it seems like it is impossible. It seems that addition and subtraction under if else cannot detect score. Is there any other way?
package com.mkyong.android;
import com.mkyong.android.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class App2Activity extends Activity {
private RadioGroup radioAnswerGroup2;
private RadioButton radioAnswerButton2;
private Button btnSubmit2;
Button button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
radioAnswerGroup2 = (RadioGroup) findViewById(R.id.radioAnswer2);
button2 = (Button) findViewById(R.id.button2);
Button button2pre = (Button) findViewById(R.id.button2pre);
Intent intent = getIntent();
final int score = intent.getIntExtra("int", -1);
final TextView result2 = (TextView) findViewById(R.id.txtResult2);
result2.setText("Result counting: " + String.valueOf(score));
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int correctId2 = (R.id.answer2b);
// get selected radio button from radioGroup
int selectedId2 = radioAnswerGroup2.getCheckedRadioButtonId();
// find the radio button by returned id
radioAnswerButton2 = (RadioButton) findViewById(selectedId2);
if (selectedId2==correctId2){
score = score + 1;
//show toast saying it is correct
//Context context = getApplicationContext();
//CharSequence text = ("You are correct!");
//int duration = Toast.LENGTH_SHORT;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
else{
score = score - 1;
//toast incorrect
//Context context = getApplicationContext();
//CharSequence text = ("You are wrong but it's ok and the answer is Data Link");
//int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
Intent intent2 = new Intent(App2Activity.this, App3Activity.class);
intent2.putExtra("int", score);
startActivity(intent2);
}
});
button2pre.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, AppActivity.class);
startActivity(intent);
}
});
}
}
Move int score to be a global variable to access it in onClick. You'll also need to remove the final keyword so the value can be changed after you initialize it.
public class YourActivity extends Activity{
int score;
public onCreate( /*...etc.*/
Simply remove final keyword from :
final int score = intent.getIntExtra("int", -1);
Because a final variable can only be initialized once, either via an initializer or an assignment statement.
Read more here.

How do you save the data of an int, and then edit the number onclick of a button?

I am trying to have it so when you click one of the answeers (Q1A1 or Q1A2) it will add a number of points to the testScore int so I can then later call that in a later class so the score they got would be posted there. Thanks to anyone who helps in advance!
here's my code,
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Test extends Activity implements OnClickListener
{
TextView Q1A1;
TextView Q1A2;
TextView test;
public static final String PREFS_NAME = "MyPrefsFile";
public static final int testScore = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Q1A1 = (TextView) findViewById(R.id.Q1A1);
Q1A2 = (TextView) findViewById(R.id.Q1A2);
Q1A1.setOnClickListener(this);
Q1A2.setOnClickListener(this);
test = (TextView) findViewById(R.id.test);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
test.setText(settings.getString("YourScore", "No Score"));
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + 10));
editor.commit();
//Intent FinalScore = new Intent(this, FinalScore.class);
//startActivity(FinalScore);
break;
case R.id.Q1A2:
break;
}
}
}
thanks for the help
You are are saving your score as an int but calling it as a string.
Change
test.setText(settings.getString("YourScore" , "No Score"));
To
test.setText(""+settings.getInt("YourScore" , 0));

Categories

Resources