Iman Marashi
Iman Marashi

Reputation: 5753

How can I define the counter is not reset by restarting activity?

Two counters are defined within my code .

When the right answer to a single user ID is added to the true_counter and the wrong answer to a user if the wrong material is added to the fales_counter , but the problem is when the activity re- load the counters to zero as .

package com.Learning.math;

import java.util.Random;

import org.w3c.dom.Text;

import com.Learning.math.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class Plus extends Activity {
private TextView num11;
private TextView num22;
public Integer no1;

public Integer no2;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.plus_page);
    // Set Numbers To TextView's
    num11 = (TextView) findViewById(R.id.num1);
    num22 = (TextView) findViewById(R.id.num2);
    Intent iin = getIntent();
    Bundle b = iin.getExtras();
    if (b != null) {
        final String numb1 = (String) b.get("from");
        final String numb2 = (String) b.get("to");
        Integer min = Integer.valueOf(numb1);
        Integer max = Integer.valueOf(numb2);
        Random r1 = new Random();
        int random1 = r1.nextInt(max + -min) + min;
        Random r2 = new Random();
        int random2 = r2.nextInt(max - min) + min;
        String str1 = String.valueOf(random1);
        String str2 = String.valueOf(random2);
        num11.setText(str1 + "");
        num22.setText(str2 + "");
        no1 = Integer.valueOf(str1);
        no2 = Integer.valueOf(str2);
    }

    final EditText answerbox = (EditText) findViewById(R.id.answer_box);
    final ImageView true_pic = (ImageView) findViewById(R.id.imageView1);
    final ImageView false_pic = (ImageView) findViewById(R.id.imageView2);
    final Handler handler = new Handler();
    final TextView afarin = (TextView) findViewById(R.id.afarin_txt);
    final TextView try_again = (TextView) findViewById(R.id.try_again_txt);
    final TextView false_counter_txt = (TextView) findViewById(R.id.true_counter);
    final TextView true_counter_txt = (TextView) findViewById(R.id.false_counter);
    // تعریف فونت طناب
    Typeface tf = Typeface
            .createFromAsset(getAssets(), "fonts/tanab_0.ttf");
    afarin.setTypeface(tf);
    try_again.setTypeface(tf);
    // /////////////
    Button btn = (Button) findViewById(R.id.button1);
    btn.setOnClickListener(new OnClickListener() {

        private int true_counter;
        private int false_counter;

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            String Answr = answerbox.getText().toString();
            Integer answer = Integer.valueOf(Answr);
            if (answer == (no2 + no1)) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Do something after 3s = 3000ms
                        startActivity(getIntent());
                    }
                }, 2000);

                hideSoftKeyboard(Plus.this);
                true_pic.setVisibility(View.VISIBLE);
                afarin.setVisibility(View.VISIBLE);
                true_counter++;
                true_counter_txt.setText(Integer.toString(true_counter));
            } else {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Do something after 3s = 3000ms
                        startActivity(getIntent());
                    }
                }, 2000);
                hideSoftKeyboard(Plus.this);
                false_pic.setVisibility(View.VISIBLE);
                try_again.setVisibility(View.VISIBLE);
                false_counter++;
                false_counter_txt.setText(Integer.toString(false_counter));
            }
        }
    });
}

// /////////// Hide Keyboard When Clicking
public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager) activity
            .getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
            .getWindowToken(), 0);
}

}

Upvotes: 1

Views: 113

Answers (4)

savepopulation
savepopulation

Reputation: 11921

You can save your counter values onSavedInstanceState

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);

  savedInstanceState.putInt("true_counter", true_counter_value);
  savedInstanceState.putInt("false_counter",false_counter_value);

}

And you can restore your counter values onCreate or onRestoreInstanceState

Other way you can save your counter values to SharedPreferences You can find details about saving and loading data from shared preferences from here: How to use SharedPreferences in Android to store, fetch and edit values

Upvotes: 1

Barend
Barend

Reputation: 17444

You'll want to override the onSaveInstanceState() method to write the counter value and use the onCreate(Bundle) method to read the counter value (null-check the bundle before use).

Using static is no good, as it'll disappear if your app is closed in the background and later resumed.

Using sharedPreferences would also work, but it's more intended for long-term storage (persisted over multiple runs of your app), while instance state is intended for short-term usage (persisted over a single run of your app). Think of it as using shared prefs to store high scores and instance state to store data for the current game.

Upvotes: 2

Waqar Ahmed
Waqar Ahmed

Reputation: 5068

declare variables as static or you can store that value in sharedpreferencess as well.

Upvotes: 0

betteroutthanin
betteroutthanin

Reputation: 7556

Quite easy actually, just make your counter static.

Upvotes: 0

Related Questions