How to save activity state after navigating?

298 views Asked by At

I have an app with 3 activities,home,calculationResult and help.What I'm trying to do is save the details of the calculations on calculationResult when the user navigates to help.So when the user is in help and presses the action bar back icon,the results of the calculation will still be there in calculationResult.

I have tried to implement this so far by following this guide: Recreating an activity,But when I implemented it the variable I'm wanting to store is not recognized when using with savedInstanceState.Below is how I have tried to do this in the result class.Can someone point out where I have gone wrong with this or if this is the correct way to accomplish saving the activity state?

public class CalcResult extends Activity implements OnClickListener{

TextView result1;

static final String MARK1 = "marking1";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);

        if (savedInstanceState != null) { 
            // Restore value of members from saved state 
            //not recognizing this variable mark1 which I'm setting to the variable that stores the result of the calculation.
            mark1 = savedInstanceState.getDouble(MARK1); 
        }

        final Intent intent1=new Intent(this,AboutActivity.class);
        final Intent intent2=new Intent(this,MainActivity.class);
        final Intent intent3=new Intent(this,MainActivity.class);

        final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
                R.layout.a,
                null);

        // Set up your ActionBar
        final ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setCustomView(actionBarLayout);

        final Button actionBarHome = (Button) findViewById(R.id.action_bar_title);
        actionBarHome.setBackgroundResource(R.drawable.ic_action_back);
        actionBarHome.setOnClickListener(this);
        actionBarHome.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {                

               startActivity(intent2);

            }

        });

        final Button actionBarInfo = (Button) findViewById(R.id.action_bar_staff);
        actionBarInfo.setBackgroundResource(R.drawable.ic_action_help);
        actionBarInfo.setOnClickListener(this);
        actionBarInfo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {                

               startActivity(intent1);

            }

        });


        final Button actionBarHoome = (Button) findViewById(R.id.action_bar_home);
        actionBarHoome.setBackgroundResource(R.drawable.appicon);
        actionBarHoome.setOnClickListener(this);
        actionBarHoome.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {                

               startActivity(intent3);

            }

        });
        result1 = (TextView)findViewById(R.id.markOne);


        Intent intent = getIntent();

        double markOne = intent.getDoubleExtra("number1", 0);

        DecimalFormat df = new DecimalFormat("#.##");

        result1.setText(String.valueOf(df.format(markOne)+"mm"));

    }


    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state
        //Also doesn't recognise markOne here ->
        savedInstanceState.putDouble(MARK1, this.markOne);


        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }
3

There are 3 answers

4
vipul mittal On BEST ANSWER

Instead of this

double markOne = intent.getDoubleExtra("number1", 0);

You should write

markOne = intent.getDoubleExtra("number1", 0);

by declaring it again you are not assigning the value to the class level markOne

Also you can try setting the lauchmode of your calculateResult activity as singleTop

 android:launchMode="singleTop"

This will use the same instance of the activity that already exist on the top of the stack so will have the same state as before.

Try calling finish in your Help activity when you move to CalculationResult activity.

for ex:

StartActivity(<Intent>);
finish();
2
Prem On

onRestoreInstanceState() is called when Activity was killed by the OS. "Such situation happen when: •orientation of the device changes (your activity is destroyed and recreated) •there is another activity in front of yours and at some point the OS kills your activity in order to free memory.

Next time when you start your activity onRestoreInstanceState() will be called."

But in your case, this might not happen.

0
Prem On

Approach i followed

I set a global varibale to act as a flag if i am launching this activity for the first time. If the global varibale is the same as what i had set, i leave the editText untouched. (in your case, result1). If the value is changed, i set the editText for this value. If the user clicks the editText even once, i track the change and store the value. When you think, the mark1 is no longer needed, you can set the value of flag again as "FIRSTENTRY". This would work.

Kindly try and let us know if you still face issues.

Step 1

Created a class to store a static Global variable.

public class Constants {        
public static String sFlag= "FIRSTENTRY";
}

Step 2

Add this piece of code after "setContentView(R.layout.result);" line in your oncreate method. Instead of TextView, i have declared result1 as EditText.

if(!Constants.sFlag.equalsIgnoreCase("FIRSTENTRY"))
        {
            result1.setText(Constants.sFlag);
        }

        result1.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub
                Constants.sFlag = result1.getText().toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                Constants.sFlag = result1.getText().toString();

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                Constants.sFlag = result1.getText().toString();
            } 

        });