I have a problem when creating a hangman game.
I'm pretty new to android, only been doing it for a week, but now i'm in a real jam.
I keep loosing an int variable's value at the same place everytime. It is the variable antallGjett (Means number fo guesses). I have pictures in an imageview there and the first is set to zero. First time it is okey, the image changes. But then next time, nothing happens. It never changes to image "hang2" on the second miss, but on the third miss it goes forward. BUT, the counter still have the value 6 at image nr 5. heres the method:
public void klikkKnapp(char[] c, Button bokstav, char[] l, char[] gjettetOrd) {
boolean bol= sjekkBokstav(c, bokstav, l, gjettetOrd);
if(bol== false) {
if(antallGjett>= 6)
antallGjett= 0;
++antallGjett; //number of guesses
String pakke= getApplicationContext().getPackageName();
image= getResources().getIdentifier(pakke+":drawable/hang"+ antallGjett+"", null, null); //
hangMan= (ImageView)findViewById(R.id.hengtmann);
if(hangMan.getId()== image) {
++antallGjett;
image= getResources().getIdentifier(pakke+":drawable/hang"+ antallGjett, null, null);
}
hangMan.setImageBitmap(BitmapFactory.decodeResource(getResources(), image));
}
if(antallGjett== 6)
showDialog(false);
else if(Arrays.equals(ord, gjettetOrd))
showDialog(true);
}
I have implementet onPause() and onResume() , but it doesent help.
Example of my onPause() method:
protected void onPause() {
super.onPause();
Context context = this.getBaseContext();
SharedPreferences sharedPref = context.getSharedPreferences("PREF_KEY", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("antallGJETT", antallGjett); // value to store
// Commit to storage
editor.commit();
}
And here onResume:
#Override
protected void onResume() {
super.onResume();
Context context = this.getBaseContext();
SharedPreferences sharedPref= context.getSharedPreferences("PREF_KEY", MODE_PRIVATE);
an
tallGjett= sharedPref.getInt("antallGJETT", antallGjett);
}
I have read and read and tried and tried, but i see no solution.. :(
Related
I have a page in my application where the user can enter a product name and it's calorie count, which it then removes from a daily calorie count which comes from another class. This works perfectly I wanted to make it so that it doesn't reset to the original value each time the page is opened (unless its a fresh install / manual reset via a button).
I came across SharedPreferences and tried to implement this, but it always comes up with the default value in my onResume method and I am not too sure why and need some assistance to figure out what I am doing wrong and how to fix it, as I will need to use this in several other classes also.
My Class:
public class CalorieTracker extends AppCompatActivity {
protected String age, calorieCount;
protected EditText itemName, kCal;
protected TextView remainingCalories;
protected Button submitBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_tracker);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
calorieCount = extras.getString("calories");
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentCount = Integer.parseInt(remainingCalories.getText().toString());
int enteredAmount = Integer.parseInt(kCal.getText().toString());
calorieCount = String.valueOf(currentCount - enteredAmount);
remainingCalories.setText(calorieCount);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("sessionCalories",remainingCalories.getText().toString());
editor.commit();
}
});
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
}
http://prntscr.com/me99dp
Image of what it looks like when I boot the application, even though the initial calorieCount value should be 2100 which I get from the previous page using the Bundle extras.
If I change the
line remainingCalories.setText(mPrefs.getString("sessionCalories","")); in my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3")); then it shows 3 initially.
Make sure that your data is updated in shared preference correctly. In Activity life cycle after onviewCreated only onResume called .
so if your current activity will go to foreground or rotate then only onResume will call again.
so solution ,in button click after set the value and get value from sharedpreference and display like this
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// first time save data
setvalueFromSharedpreference()
}
});
public setvalueFromSharedpreference()
{
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
when I boot the application, even though the initial calorieCount
value should be 2100 which I get from the previous page using the
Bundle extras.
If I change the line
remainingCalories.setText(mPrefs.getString("sessionCalories","")); in
my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3"));
then it shows 3 initially.
Reason editText remainingCalories always have default (sharedpreference value) is because onResume method is called after onCreate in activity's lifecycle. Thats why, Bundle extras value is being overwritten by sharedpreference value.
You can achieve this in onCreate method by checking if Intent extras has value. If yes, then set that value otherwise set the sharedPrefrence's value as follows
#Override
protected void onCreate(Bundle savedInstanceState) {
...
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
calorieCount = mPrefs.getString("sessionCalories","");
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
if(!calorieCount.isEmpty)
remainingCalories.setText(calorieCount);
else
{
calorieCount = extras.getString("calories");
}
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
}
And remove the sharedPreference setting from onResume.
Hope it helps cheers:)
I have a piece of code that I only want to run the very first time a particular OnCreate() method is called (per app session), as opposed to every time the activity is created. Is there a way to do this in Android?
protected void onCreate(Bundle savedInstanceState) has all you need.
If savedInstanceState == null then it is the first time.
Hence you do not need to introduce extra -static- variables.
use static variable.
static boolean checkFirstTime;
use static variable inside your activity as shown below
private static boolean DpisrunOnce=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_once);
if (DpisrunOnce){
Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
}else{
//not run do yor work here
Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
DpisrunOnce =true;
}
}
use sharedpreference...set value to true in preference at first time...at each run check if value set to true...and based on codition execute code
For Ex.
SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
if (!preferences.getBoolean("isFirstTime", false)) {
//your code goes here
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}
Hello Together I startet to write my first Android app and I tried to use the SharedPreferences to have the possibility to store some strings.
I can Type in different names and in the onStop() I put them into the SharedPreferences and after that i make a commit. Has someone a solution that Preferences are shown on the next Activity immediatly? Because at the moment I have to switch back to the Activity where I Typed in the names and if I immediatly switch back to the Activity where the names shall be shown they appear.
protected void onStop() {
SharedPreferences.Editor edit = set.edit();
for(int x=0;x<counterM;x++){
edit.putString("playerM"+x, playersMale.get(x));
}
for(int x=0;x<counterF;x++){
edit.putString("playerF"+x, playersFemale.get(x));
}
edit.putInt("counter", counterF + counterM);
edit.commit();
super.onStop();
}
and here is the onCreate() where I load the name...
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
set = this.getSharedPreferences("MY_COUNT",0);
this.setContentView(R.layout.decisionscreen);
Random r = new Random();
int i = set.getInt("counter",1000);
int x = r.nextInt(i);
name = set.getString("playerM"+x, "no Players found");
TextView t = (TextView)findViewById(R.id.nameView);
t.setText(name+" "+i);
dareButton();
truthButton();
}
I hope someone can figure out what my problem is.
Try to put the shared preferences editor stuff in the onPause override. It will be called as soon as you switch the activity.
I have a preference Activity, at first when I chance a preference the onPreferenceChange is triggered once as expected.
However, after some time (going to different activities and such) the onPreferenceChange is called twice.
I see in the debugger that the WeakHashMap for the mListeners is 1 in the beginning and then becomes greater than 1, but not sure why?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPrefs();
int preferencesResource = 0; // R.xml.preferences;
preferencesResource = getResources().getIdentifier("pref", "xml",
getPackageName());
addPreferencesFromResource(preferencesResource);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences arg0,
String arg1) {
// Why is this called once then sometimes twice!!
Log.i("PreferencesActivity", "OnPreferenceChanged()");
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
}
protected void onDestroy() {
super.onDestroy();
listener = null;
prefs.unregisterOnSharedPreferenceChangeListener(listener);
prefs = null;
}
public Preferences getPrefs() {
if (prefs == null) prefs = new Preferences(this);
return prefs;
}
You've placed unregisterOnSharedPreferenceChangeListener() in onDestroy() and it's not called on all activity restarts.
Look at the activity lifecycle diagram. Conclusion is that proper way to do this is to place registerOnSharedPreferenceChangeListener() and unregisterOnSharedPreferenceChangeListener() in onResume() and onPause() respectively.
This isn't for a LiveWallpaper by any chance is it? It sounds to me like you have two instances of the same class running(I.E. The LiveWallpaper itself as well as the preview because you're in settings). If it seems like they happen instantly right on top of each other and there is no delay than most likely you have the same listener running twice.
I have a list view. I am getting check box when I check it.
But I want to get same status when I restart the application. If is there any way to do it please reply me.
I am really new to android.
my code is follows:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//I am getting status of check box here. If I click on file check box is appearing to me. //I want to be store always for true.
String keyword = value[position];
mediaPlayer.reset();
try
{
mediaPlayer.setDataSource("/sdcard/"+keyword+".mp4");
mediaPlayer.prepare();
mediaPlayer.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
thanks in advance.
You may use SharedPreference for your values to stay even if your application gets closed. Use a default value in your constants file.
For eg:
Create a class for storing all SharedPreferences.
In that give,
private static SharedPreferences sharedPref;
public static final String PREFERENCE_DATA = "some data";
Inside constructor give,
sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
Add setter/getter methods for each preference value.
public static void setPreferenceData(String data) {
if (sharedPref != null) {
Editor editor = sharedPref.edit();
editor.putString(PREFERENCE_DATA, data);
editor.commit();
}
}
public static String getPreferenceData() {
String data = "data";
if (sharedPref != null) {
status = sharedPref.getString(PREFERENCE_DATA,your variable name stored in constants);
}
return data;
}
So when you want to set any data, use setPreferenceData and when you want to fetch value use getPreferenceData.
You need to save the state of the checkbox in the onPause method of your activity. After onPause was called the system can close your application without any further warning as described in the Activity Documentations
To save the checked items your onPause method would look something like this:
#Override
protected void onPause() {
super.onPause();
long[] checkedBoxes = getListView.getCheckedItemIds();
setPreferenceData(checkedBoxes);
}
You only have to modify Mathews Code in a way that allows you to save long Arrays.
Now you can get these values from the sharedPreferences file in the onCreate method and set the checkboxes accordingly in your Adapter code.