简体   繁体   中英

Keep the data save in sharedPreference although pressed back button - Android Studio

I have some problem as I mention in my question. I have two activity, Activity A and Activity B. When I Enter some data in Activity A, then I press next button, it will redirect to Activity B. At Activity B, I also enter some data. When I press back button, the data at Activity A is display as I entered before. When I press next button, the data that I entered at Activity B is missing. Below is my SharedPreferences code.

Activity A:

public class NewSuggestion extends AppCompatActivity {

private EditText etYear, etMonth, etTitle, etOwnValue;
private RadioGroup rgSuggestWill;
private RadioButton radioButton;
private Button btnNext;
ArrayAdapter<CharSequence> adapter;
private Spinner spReviewer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_suggestion);

    final ActionBar abar = getSupportActionBar();
    View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
    ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.MATCH_PARENT,
            Gravity.CENTER);
    TextView tvTitle = viewActionBar.findViewById(R.id.title);
    tvTitle.setText("NEW SUGGESTION");
    abar.setCustomView(viewActionBar, params);
    abar.setDisplayShowCustomEnabled(true);
    abar.setDisplayShowTitleEnabled(false);
    //abar.setDisplayHomeAsUpEnabled(true);
    abar.setHomeButtonEnabled(true);

    etTitle = findViewById(R.id.etTitle);
    etYear = findViewById(R.id.etYear);
    etMonth = findViewById(R.id.etMonth);
    rgSuggestWill =findViewById(R.id.rgSuggestWill);
    final Calendar c = Calendar.getInstance();
    String mm = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
    int yy = c.get(Calendar.YEAR);
    etYear.setText(new StringBuilder().append(yy));
    etMonth.setText(new StringBuilder().append(mm));

    spReviewer = findViewById(R.id.spReviewer);
    adapter = ArrayAdapter.createFromResource(this,R.array.reviewer,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spReviewer.setAdapter(adapter);
    spReviewer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


    btnNext = findViewById(R.id.btnNext);
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("title",etTitle.getText().toString());
            editor.putString("year",etYear.getText().toString());
            editor.putString("month",etMonth.getText().toString());

            // get selected radio button from radioGroup
            int selectedId = rgSuggestWill.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioButton = findViewById(selectedId);
            editor.putString("suggestionwill",radioButton.getText().toString());
            if (spReviewer.getSelectedItem().toString().equals("Please choose")){

                AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
                alertDialog.setTitle("Alert");
                alertDialog.setMessage("Please choose your reviewer");
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();
            }else{
                editor.putString("reviewer",spReviewer.getSelectedItem().toString());
                Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
                startActivity(intent);
            }
            editor.apply();
        }
    });

}

@Override
public void onBackPressed() {

            Intent intent = new Intent(NewSuggestion.this, DashboardApp.class);
            startActivity(intent);
}

}

Activity B:

public class NewSuggestion2 extends AppCompatActivity {

private EditText etPresent, etDetails, etBenefit;
private ImageView imgAttach,btnCamera,btnGallery;
private Button btnNext,btnClear;
private Intent intent;
private Bitmap bitmap;
private int REQUEST_CODE = 1;
public  static final int RequestPermissionCode  = 1 ;

public static final String DEFAULT = "N/A";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_suggestion2);

    final ActionBar abar = getSupportActionBar();
    View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
    ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.MATCH_PARENT,
            Gravity.CENTER);
    TextView tvTitle = viewActionBar.findViewById(R.id.title);
    tvTitle.setText("NEW SUGGESTION (Cont..)");
    abar.setCustomView(viewActionBar, params);
    abar.setDisplayShowCustomEnabled(true);
    abar.setDisplayShowTitleEnabled(false);
    //abar.setDisplayHomeAsUpEnabled(true);
    abar.setHomeButtonEnabled(true);


    etPresent = findViewById(R.id.etPresent);
    etDetails = findViewById(R.id.etDetails);
    etBenefit = findViewById(R.id.etBenefit);

    imgAttach = findViewById(R.id.imgAttach);

    btnCamera=findViewById(R.id.btnCamera);
    EnableRuntimePermission();
    btnCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 7);
        }
    });
    btnGallery=findViewById(R.id.btnGallery);
    btnGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Photo"),REQUEST_CODE);

        }
    });
    btnNext = findViewById(R.id.btnNext);
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("present", etPresent.getText().toString());
                editor.putString("details", etDetails.getText().toString());
                editor.putString("benefit", etBenefit.getText().toString());
                editor.apply();


            Intent intent = new Intent(NewSuggestion2.this,ConfirmSuggestion.class);
            startActivity(intent);
        }
    });
    btnClear = findViewById(R.id.btnClear);
    btnClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imgAttach.setImageBitmap(null);
        }
    });

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 7 && resultCode == RESULT_OK) {

        Bitmap bitmap = (Bitmap) data.getExtras().get("data");

        imgAttach.setImageBitmap(bitmap);
    }

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){

        Uri uri = data.getData();
        try{
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            imgAttach.setImageBitmap(bitmap);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

public void EnableRuntimePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(NewSuggestion2.this,
            Manifest.permission.CAMERA))
    {

        Toast.makeText(NewSuggestion2.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();

    } else {

        ActivityCompat.requestPermissions(NewSuggestion2.this,new String[]{
                Manifest.permission.CAMERA}, RequestPermissionCode);

    }
}

@Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {

    switch (RC) {

        case RequestPermissionCode:

            if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(NewSuggestion2.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();

            } else {

                Toast.makeText(NewSuggestion2.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();

            }
            break;
    }
}

@Override
public void onBackPressed() {


}

}

Assign value to present,details,benefit from sharedpref

   SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();

 etPresent = findViewById(R.id.etPresent);
    etDetails = findViewById(R.id.etDetails);
    etBenefit = findViewById(R.id.etBenefit);

etPresent.setText(sharedPref.getString("present", ""));
etDetails.setText(sharedPref.getString("details", ""));
etBenefit.setText(sharedPref.getString("benefit", ""));

In Activity B make sure you save data in onBackPressed()

@Override
public void onBackPressed() {
    editor.putString("present", etPresent.getText().toString());
    editor.putString("details", etDetails.getText().toString());
    editor.putString("benefit", etBenefit.getText().toString());
    editor.apply();     
    super.onBackPressed();
}

You have to override the onBackPress() method.In Activity B it is necessary to put data in to SharedPreferences.

@Override
public void onBackPressed() {
    SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("present", etPresent.getText().toString());
    editor.putString("details", etDetails.getText().toString());
    editor.putString("benefit", etBenefit.getText().toString());    
    editor.commit();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM