I create a mini game . The User need to answer my question in 2 seconds, if user answer true , the score will increase 1 , and if user answer wrong - Game over and the score become to 0.
I want to use SharedRefences so that I can save the score when the user play again . But it's not working .
My CountDownTimer:
public void start_game() {
flag = false;
btnTrue.setClickable(true);
btnWrong.setClickable(true);
a = (int) (Math.random() * 6);
b = (int) (Math.random() * 6);
sum = (int) (Math.random() * 11);
tvDetails.setText(a + " + " + b + " = " + sum);
proTime.setSecondaryProgress(0);
timer = new CountDownTimer(3000, 10) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
btnTrue.setClickable(false);
btnWrong.setClickable(false);
if (flag) {
tmp++;
tvScore.setText("" + tmp);
start_game();
} else {
ShowDialogs();
tmp = 0;
tvScore.setText("" + tmp);
}
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
proTime.setSecondaryProgress(proTime.getSecondaryProgress() + 10);
}
};
timer.start();
}
public void ShowDialogs() {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(false);
tvNowScore = (TextView) dialog.findViewById(R.id.NowScore);
tvHighScore = (TextView) dialog.findViewById(R.id.HighScore);
ImageView btnRep = (ImageView) dialog.findViewById(R.id.Rep);
ImageView btnExit = (ImageView) dialog.findViewById(R.id.Exit);
ResPreferences();
int HighScore = Integer.parseInt(tvHighScore.getText().toString());
int Score = Integer.parseInt(tvScore.getText().toString());
if (Score > HighScore) {
HighScore = Score;
SavingPreferences();
}
tvNowScore.setText("" + Score);
tvHighScore.setText("" + HighScore);
btnExit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
System.exit(0);
}
});
btnRep.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.cancel();
if (timer != null) {
timer.cancel();
timer = null;
}
start_game();
}
});
dialog.show();
}
I can't save a score when the game finish.
This is my Save Preferences
public void SavingPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
SharedPreferences.Editor editor = pre.edit();
String HighScore = tvHighScore.getText().toString();
editor.putString("HighScore", HighScore);
editor.commit();
}
This is Restrore Pre:
public void ResPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
String score = pre.getString("HighScore", "0");
tvHighScore.setText(score);
}
Try this :
public void SavingPreferences() {
SharedPreferences pre = getSharedPreferences(PrefName, MODE_PRIVATE);
String score = null;
if(pre.contains("HighScore")){
score = pre.getString("HighScore", "0");
}
SharedPreferences.Editor editor = pre.edit();
String HighScore = tvHighScore.getText().toString();
if(score != null && Integer.parseInt(score) > Integer.parseInt(HighScore )){
editor.putString("HighScore", score);
} else {
editor.putString("HighScore", HighScore);
}
editor.commit();
}
Related
I have tried to make an countdown timer in a list veiw implementation. Each list item has a separate countdown timer that can be started or stopped. However I have noticed that if I add the first timer in list and set its time. When I start the timer it starts two seconds less than the actual time. e.g If I added a count down of 12 seconds. Then it will start counting from 10. But when the countdown is taking place and I add another new timer and set its time, it starts on the exact given time. The new counter starts at the wrong time only when either there is no other counter in the list or when all counters are already stopped and not counting down. Similarly it will only start the right time only when other timers are counting down. Would really appreciate if someone can help me figure out where is the problem. I have been looking at the code for days.
Here's my Adapter class
public class CustomAdapterCounter extends ArrayAdapter<CounterData> {
private final LayoutInflater mInflater;
Context context;
Uri sound = Uri.parse("android.resource://com.tattooalarmclock.free/" + R.raw.counter);
String counterString = "";
private List<ViewHolder> lstHolders;
private List<CounterData> list = new ArrayList<CounterData>();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
// if(!holder.counterData.isStopped)
holder.updateTimeRemaining(System.currentTimeMillis());
}
}
}
};
public CustomAdapterCounter(Context context, List<CounterData> l) {
super(context, 0, l);
this.context = context;
lstHolders = new ArrayList<>();
list = l;
mInflater = LayoutInflater.from(context);
for(int i=0; i<list.size(); i++) {
CounterData[] array = list.toArray(new CounterData[list.size()]);
if(!array[i].isStopped)
startUpdateTimer();
}
}
public double getScreenSize() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int dens = dm.densityDpi;
double wi = (double) width / (double) dens;
double hi = (double) height / (double) dens;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}
public boolean getListSharedPreferences() {
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getString("CL", null) != null) {
counterString = sharedPreferences.getString("CL", null);
Gson gson = new Gson();
TypeToken<List<CounterData>> token = new TypeToken<List<CounterData>>() {};
list = gson.fromJson(counterString, token.getType());
return true;
}
else
return false;
}
public void saveListSharedPreferences(List counterList) {
Gson gson = new Gson();
counterString = gson.toJson(counterList);
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("CL", counterString).commit();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
if(getScreenSize() <= 4 )
convertView = mInflater.inflate(R.layout.list_view_counter_small, parent, false);
else
convertView = mInflater.inflate(R.layout.list_view_item_counter, parent, false);
holder.counterTextView = (TextView) convertView.findViewById(R.id.counterTextView);
holder.stopCounter = (Button) convertView.findViewById(R.id.counterStopInList);
holder.startCounter = (Button) convertView.findViewById(R.id.counterStartInList);
holder.deleteCounter = (Button) convertView.findViewById(R.id.deleteCounter);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData2(getItem(position));
final ViewHolder finalHolder = holder;
holder.stopCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long store = finalHolder.counterData.expirationTime - System.currentTimeMillis();
finalHolder.counterData.isStopped = true;
finalHolder.counterData.expirationTime = store;
finalHolder.stopCounter.setEnabled(false);
finalHolder.stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
/* if(getListSharedPreferences()) {
System.out.println("List before change in stop button " + list.toString());
list = stringToArray(counterString, CounterData[].class);
list.set(position, finalHolder.counterData);
System.out.println("List before change in stop button " + list.toString());
saveListSharedPreferences(list);
}
else {
System.out.println(list.toString());
list.set(position, finalHolder.counterData);
System.out.println(list.toString());
saveListSharedPreferences(list);
}
*/
}
});
holder.startCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
finalHolder.counterData.isStopped = false;
//finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
//finalHolder.setData(finalHolder.counterData);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.stopCounter.setEnabled(true);
finalHolder.stopCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
startUpdateTimer();
/* if(getListSharedPreferences()) {
list = stringToArray(counterString, CounterData[].class);
System.out.println("List before change in start button " + list.toString());
list.set(position, finalHolder.counterData);
System.out.println("List after change in start button " + list.toString());
saveListSharedPreferences(list);
}
else {
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
} */
}
});
final ViewHolder finalHolder1 = holder;
holder.deleteCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* if(finalHolder1.mediaPlayer.isPlaying()) {
finalHolder.mediaPlayer.stop();
// finalHolder.counterData.isSoundPlayedBefore = true;
} */
list.remove(position);
notifyDataSetChanged();
saveListSharedPreferences(list);
}
});
return convertView;
}
}
class ViewHolder {
public TextView counterTextView;
//public List<Long> l;
CounterData counterData;
Button startCounter;
Button stopCounter;
Button deleteCounter;
boolean stop = false;
long timeDiff;
// Context context;
// MediaPlayer mediaPlayer;
// List<CounterData> counterDataList;
public void setData(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void setData2(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
if (!counterData.isStopped) {
timeDiff = counterData.expirationTime - currentTime;
//System.out.println("Time Diff Inside Method " + timeDiff);
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
stopCounter.setEnabled(true);
stopCounter.getBackground().setColorFilter(null);
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
} else {
counterTextView.setText("Times Up");
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
// Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
// v.vibrate(5000);
/* if(!counterData.isSoundPlayedBefore) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
});
counterData.isSoundPlayedBefore = true;
if(findIndex(counterData) != -1) {
int index = findIndex(counterData);
counterDataList.set(index,counterData);
saveListSharedPreferences(counterDataList);
}
} */
}
}
else {
long store = counterData.expirationTime + System.currentTimeMillis() - currentTime;
int seconds = (int) (store / 1000) % 60;
int minutes = (int) ((store / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(store);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
startCounter.setEnabled(true);
startCounter.getBackground().setColorFilter(null);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
}
}
}
And here's my CounterData class
class CounterData {
long expirationTime;
boolean isStopped;
boolean isSoundPlayedBefore;
int id;
public CounterData(long expirationTime, int id) {
this.expirationTime = expirationTime;
isStopped = true;
isSoundPlayedBefore = false;
this.id = id;
}
public String toString() {
return String.valueOf("Remaining Time: " + TimeUnit.MILLISECONDS.toMinutes(this.expirationTime) + ":" + TimeUnit.MILLISECONDS.toSeconds(this.expirationTime));
}
public void setCounterID(int id) {
this.id = id;
}
public int getCounterID() {
return this.id;
}
}
And I add the time from number pickers of Hour, Minute and Second.
case R.id.counterStartStopButton:
long hour = TimeUnit.HOURS.toMillis(numberPickerHour.getValue());
long minute = TimeUnit.MINUTES.toMillis(numberPickerMinute.getValue());
long second = TimeUnit.SECONDS.toMillis(numberPickerSecond.getValue());
// if(getListSharedPreferences()) {
if(getCounterIDSharedPreferences()) {
counterID = counterID + 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
else {
counterID = 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
UPDATE
Here's the shared preferences code
public void saveCounterIDSharedPreferences(int id) {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putInt("Counter ID123", id).commit();
}
public boolean getCounterIDSharedPreferences() {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getInt("Counter ID123", -1) != -1) {
counterID = sharedPreferences.getInt("Counter ID123", -1);
return true;
}
else
return false;
}
What turned out to work for me was changing the timer task as following:
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 500, 500);
}
Please help me, code below
The textview is always 0 when i close and start my app.
EDIT
The full code is now added.
TextView txt = (TextView)findViewById(R.id.textView23);
int mynum1 = ea1.TimeCounter++;
int mynum2 = ea2.TimeCounter++;
int mynum3 = ea3.TimeCounter++;
int mynum4 = ea4.TimeCounter++;
int mynum5 = ea5.TimeCounter++;
int mynum6 = ea6.TimeCounter++;
in = (mynum1) + (mynum2) + (mynum3) + (mynum4) + (mynum5) + (mynum6) ;
txt.setText(Integer.toString(in));
TextView tt = (TextView)findViewById(R.id.textView26);
SharedPreferences sps = getSharedPreferences(PREFS, 0);
String ss = sps.getString("Score", "Nothing Found");
tt.setText(ss);
Button btn = (Button)findViewById(R.id.button8);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView txt = (TextView)findViewById(R.id.textView23);
TextView tt = (TextView)findViewById(R.id.textView26);
if (Integer.parseInt(txt.getText().toString()) < Integer.parseInt(tt.getText().toString())) {
String current = txt.getText().toString();
SharedPreferences sp = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Score", in);
editor.commit();
tt.setText(current);
}
else if(Integer.parseInt(txt.getText().toString()) > Integer.parseInt(tt.getText().toString())) {
SharedPreferences sps = getSharedPreferences(PREFS, 0);
String ss = sps.getString("Score", "Nothing Found");
tt.setText(ss);
}
}
});
So now i got an answer
new Thread(new Runnable() {
public void run() {
TextView txt = (TextView)findViewById(R.id.textView23);
int mynum1 = ea1.TimeCounter++;
int mynum2 = ea2.TimeCounter++;
int mynum3 = ea3.TimeCounter++;
int mynum4 = ea4.TimeCounter++;
int mynum5 = ea5.TimeCounter++;
int mynum6 = ea6.TimeCounter++;
in = (mynum1) + (mynum2) + (mynum3) + (mynum4) + (mynum5) + (mynum6) ;
txt.setText(Integer.toString(in));
TextView tt = (TextView)findViewById(R.id.textView26);
SharedPreferences sps = getSharedPreferences(PREFS, 0);
String ss = sps.getString("Score", "0");
tt.setText(ss);
Button btn = (Button)findViewById(R.id.button8);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView txt = (TextView)findViewById(R.id.textView23);
TextView tt = (TextView)findViewById(R.id.textView26);
if (Integer.parseInt(txt.getText().toString()) > Integer.parseInt(tt.getText().toString())) {
String current = Integer.toString(in);
SharedPreferences sp = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Score", current);
editor.commit();
tt.setText(current);
}
else if(Integer.parseInt(txt.getText().toString()) < Integer.parseInt(tt.getText().toString())) {
SharedPreferences sps = getSharedPreferences(PREFS, 0);
String ss = sps.getString("Score", "Nothing Found");
tt.setText(ss);
}
}
});
}
}).start();
}
I have a simple shop activity which uses SharedPreferences to store various data. The problem is that when I click on purchase, I can purchase it multiple times and each time it takes the money from the coins value away. Please help me with this.
This is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getActionBar().hide();
setContentView(R.layout.shop_layout);
ImageButton lives = (ImageButton) findViewById(R.id.lives);
final Button hardmode = (Button) findViewById(R.id.hardmode);
final Button reversedMode = (Button) findViewById(R.id.reversedmode);
final SharedPreferences shop = getSharedPreferences("Shop", Context.MODE_PRIVATE);
final int[] livesPrice = {shop.getInt("livesPrice", 10)};
final int[] hardmodePrice = {shop.getInt("hardmodePrice", 15)};
final int[] reversedModePrice = {shop.getInt("reverseModePrice", 20)};
final int[] coins = {shop.getInt("money", 10000)};
final boolean[] hardmodeBoolean = {shop.getBoolean("hardmode", false)};
final boolean[] reversedModeBoolean = {shop.getBoolean("reversedMode", false)};
if(hardmodeBoolean[0]){
hardmode.setText("Purchased");
}
if(reversedModeBoolean[0]){
reversedMode.setText("Purchased");
}
TextView price1 = (TextView) findViewById(R.id.price1);
final TextView money = (TextView) findViewById(R.id.money);
Typeface tf = Typeface.createFromAsset(getAssets(), "font/cricket.ttf");
price1.setTypeface(tf);
price1.setText("=" + livesPrice[0]);
money.setTypeface(tf);
money.setText("Coins " + String.valueOf(coins[0]));
lives.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (coins[0] >= livesPrice[0]) {
coins[0] = coins[0] - livesPrice[0];
livesPrice[0] = livesPrice[0] + 10;
int numberOfLives = shop.getInt("numberOfLives", 1);
numberOfLives = numberOfLives + 1;
SharedPreferences.Editor editor = shop.edit();
editor.putInt("numberOfLives", numberOfLives);
editor.putInt("money", coins[0]);
editor.commit();
money.setText("Coins " + String.valueOf(coins[0]));
}
}
});
hardmode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = shop.edit();
if (coins[0] >= hardmodePrice[0]) {
coins[0] = coins[0] - hardmodePrice[0];
editor.putBoolean("hardmode", true);
editor.putInt("hardmodePrice", 0);
editor.putInt("money", coins[0]);
editor.apply();
money.setText("Coins " + String.valueOf(coins[0]));
hardmode.setText("Purchased");
hardmodeBoolean[0] = shop.getBoolean("hardmode", true);
}
}
});
reversedMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = shop.edit();
if (coins[0] >= reversedModePrice[0]) {
coins[0] = coins[0] - reversedModePrice[0];
editor.putBoolean("reversedMode", true);
editor.putInt("reversedModePrice", 0);
editor.putInt("money", coins[0]);
editor.apply();
money.setText("Coins " + String.valueOf(coins[0]));
reversedMode.setText("Purchased");
reversedModeBoolean[0] = shop.getBoolean("reversedMode", true);
}
}
});
}
try changing
coins[0] = coins[0] - livesPrice[0];
To
coins[0] -= livesPrice[0] ;
I am using the below class to rate my app. But the every time I do this, it says "Requested item not found". but the link < play.google.com/store/apps/details?id=com.xxx.xxx > works perfectly in the browser. Why is it not working here?
One more thing I noticed that if I change the package name to the same of some other app, it works. Is there any chance that something might have been missed while uploading the previous version?
public class apprater {
private final static String APP_TITLE = "abcd";
private final static String APP_PNAME = "com.xxx.xxx";
private final static int DAYS_UNTIL_PROMPT = 3;
private final static int LAUNCHES_UNTIL_PROMPT = 7;
public static void app_launched(Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
if (prefs.getBoolean("dontshowagain", false)) { return ; }
SharedPreferences.Editor editor = prefs.edit();
// Increment launch counter
long launch_count = prefs.getLong("launch_count", 0) + 1;
editor.putLong("launch_count", launch_count);
// Get date of first launch
Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
if (date_firstLaunch == 0) {
date_firstLaunch = System.currentTimeMillis();
editor.putLong("date_firstlaunch", date_firstLaunch);
}
// Wait at least n days before opening
if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= date_firstLaunch +
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
showRateDialog(mContext, editor);
}
}
editor.commit();
}
public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
final Dialog dialog = new Dialog(mContext);
dialog.setTitle("Rate " + APP_TITLE);
LinearLayout ll = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(mContext);
tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
tv.setWidth(240);
tv.setPadding(4, 0, 4, 10);
ll.addView(tv);
Button b1 = new Button(mContext);
b1.setText("Rate " + APP_TITLE);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
System.out.println("eeeeeeeeeeeee: "+APP_PNAME);
dialog.dismiss();
}
});
ll.addView(b1);
Button b2 = new Button(mContext);
b2.setText("Remind me later");
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
ll.addView(b2);
Button b3 = new Button(mContext);
b3.setText("No, thanks");
b3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (editor != null) {
editor.putBoolean("dontshowagain", true);
editor.commit();
}
dialog.dismiss();
}
});
ll.addView(b3);
dialog.setContentView(ll);
dialog.show();
}
}
This what I am using now:
public void onClick(View v) {
final String appName = APP_PNAME;
try
{
mContext.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=com.xxx.xxx")));
}
catch (android.content.ActivityNotFoundException anfe)
{
mContext.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id=com.xxx.xxx")));
}
// mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
dialog.dismiss();
}
Try this one
final String appName = getPackageName();
try
{
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id="+ appName)));
}
catch (android.content.ActivityNotFoundException anfe)
{
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appName)));
}
I want to save my Activity state while I swipe between activities but I cannot. Some things are saved and the others dont. I think it has to do somehow with the gestureListener I'm impementing but I'm not sure.
When I swipe to a different activity and then back to this one - the AsyncTask is still running and the Handler is still updating the GUI, however, the views I have displaying in this activity and the buttons are all in their initial configuration.
what am I doing wrong?
public class Main extends Activity implements OnClickListener,
SimpleGestureListener {
/** Called when the activity is first created. */
static String checkedIN = "";
private int hoursSum;
private int minutesSum;
static int dayIs;
static String madeSoFar = "";
static int hoursCount = 0;
static String formattedSeconds = "";
static String formattedMinutes = "";
public static NumberFormat formatter = new DecimalFormat("#0.00");
static boolean killcheck = false;
static String time = "";
static Handler mHandler;
private boolean clicked = false;
private boolean wasShift = false;
static String startString;
static String finishString;
private SimpleGestureFilter detector;
private Typeface tf, tf2, roboto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// **************** Set Fonts **************
roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf");
tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf");
tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf");
// **************** Gesture implementation ************
detector = new SimpleGestureFilter(this, this);
// **************** Date and Time Objects *************
final Date date = new Date();
final Date today = Calendar.getInstance().getTime();
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
final String DateInString = DF.format(today);
String myString = DateFormat.getDateInstance().format(date);
final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay);
dateDisplay.setText(myString);
final DBAdapter DB = new DBAdapter(this);
// ************* Apply custom fonts ***************
TextView Title = (TextView) findViewById(R.id.textView2);
Title.setTypeface(tf);
final TextView Author = (TextView) findViewById(R.id.textView3);
Author.setTypeface(roboto);
TextView Current = (TextView) findViewById(R.id.textView1);
Current.setTypeface(roboto);
DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1);
DG.setTypeface(roboto);
TextView dater = (TextView) findViewById(R.id.date);
dater.setTypeface(roboto);
TextView dateDisp = (TextView) findViewById(R.id.dateDisplay);
dateDisp.setTypeface(roboto);
CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1);
CV.setTypeface(roboto);
// *************************************************//
final Button checkIn = (Button) findViewById(R.id.CheckIn);
checkIn.setTypeface(roboto);
CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1);
Boolean enable = false;
check.setEnabled(enable);
mHandler = new Handler() {
public void handleMessage(Message msg) {
time = "Time: " + hoursCount + ":" + formattedMinutes + ":"
+ formattedSeconds + " Money: " + madeSoFar;
Author.setText(time);
}
};
// **************** Click Listener for first Check In Button
checkIn.setOnClickListener(new OnClickListener() {
int startHours;
int startMinutes;
int finishHours;
int finishMinutes;
#Override
public void onClick(View v) {
// Check Out
if (clicked == true) {
killcheck = true;
checkedIN = "Check In";
checkIn.setText(checkedIN);
finishHours = Utility.getHoursTime();
finishMinutes = Utility.getMinutesTime();
finishString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
clicked = false;
wasShift = true;
hoursSum = finishHours - startHours;
minutesSum = finishMinutes - startMinutes;
// Check In
} else if (clicked == false) {
checkedIN = "Check Out";
checkIn.setText(checkedIN);
killcheck = false;
new ShiftProgress().execute();
startHours = Utility.getHoursTime();
startMinutes = Utility.getMinutesTime();
startString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
String s = "In Shift ";
CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1);
radio.setText(s);
clicked = true;
}
}
});
Button addShift = (Button) findViewById(R.id.addShift);
addShift.setTypeface(tf2);
// **************** On click listener for adding a shift
addShift.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (wasShift == true) {
changeDateToString(DateInString);
DB.open();
final Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
int count = cursor.getPosition();
final int position = count + 2;
cursor.moveToNext();
GregorianCalendar GC = new GregorianCalendar();
DB.addToDBTotal(DateInString, "Money: " + madeSoFar,
hoursSum, minutesSum,
Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)),
position, startString, finishString);
DBAdapter.close();
wasShift = false;
printAny(getApplicationContext(), "Added to Shifts",
Toast.LENGTH_SHORT);
} else {
printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT);
}
}
});
}
// **************** METHOD DECLERATIONS ****
public void viewShifts() {
Intent myIntent = new Intent(Main.this, Shifts.class);
startActivity(myIntent);
}
public void changeDateToString(String s) {
Utility.INSTANCE.setDate(s);
}
public void changeDurationToString(String s) {
Utility.INSTANCE.setDuration(s);
}
public void printAny(Context c, CharSequence s, int i) {
Context context = c;
CharSequence text = s;
final int duration = i;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.exit:
System.exit(1);
DBAdapter.close();
return true;
case R.id.view:
viewShifts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
public class ShiftProgress extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count = 0;
int seconds = 0;
int minutesTime = 0;
int minutesCount = 1;
for (;;) {
if (seconds % 60 == 0) {
minutesTime = count / 60;
seconds = 0;
}
if (seconds < 10) {
formattedSeconds = String.format("%02d", seconds);
}
else if (seconds >= 10) {
formattedSeconds = String.valueOf(seconds);
}
if (minutesTime < 10) {
formattedMinutes = String.format("%02d", minutesTime);
}
else if (minutesTime >= 10) {
formattedMinutes = String.valueOf(minutesTime);
}
if (minutesTime % 60 == 0) {
hoursCount = minutesCount / 60;
minutesTime = 0;
}
double sal = 40;
double SEC = 3600;
double salper = count * (sal / SEC);
madeSoFar = String.valueOf(formatter.format(salper));
try {
mHandler.obtainMessage(1).sendToTarget();
Thread.sleep(1000);
seconds++;
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (killcheck) {
break;
}
}
// int length = count /360;
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
#Override
public void onSaveInstanceState() {
// TODO Auto-generated method stub
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
checkedIN = savedInstanceState.getString("checkIN");
clicked = savedInstanceState.getBoolean("button");
Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG);
}
#Override
public void onPause(Bundle b) {
// TODO Auto-generated method stub
b.putString("checkIN", checkedIN);
b.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("checkIN", checkedIN);
outState.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
// etc.
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG)
.show();
}
}
You should not keep your Async task running in the background when your activity is send to the background. Your activity can be quit at any time so that you wouldn't have a reference to your activity anymore.
Regarding the preservation of state you could have a look at Activity.onRetainNonConfigurationInstance()