尽管按下返回按钮,但仍将数据保存在sharedPreference中-Android Studio

时间:2019-04-29 04:37:37

标签: java android sharedpreferences

我在提问中提到了一些问题。我有两个活动,活动A和活动B。当我在活动A中输入一些数据时,然后按下一步按钮,它将重定向到活动B。在活动B中,我也输入了一些数据。当我按下后退按钮时,活动A上的数据将按我之前输入的方式显示。当我按下下一步按钮时,我在活动B中输入的数据丢失了。以下是我的SharedPreferences代码。

活动A:

公共类NewSuggestion扩展了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);
}

}

活动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() {


}

}

2 个答案:

答案 0 :(得分:0)

从sharedpref分配呈现的值,详细信息,收益

public void UnitTest()
{            
    Action<MyChild> processor;
    processor = DoSomethingBy_MyChild;
    processor(new MyChild());             //OK

    processor = DoSomethingBy_MyParent; 
    processor(new MyChild());             //OK

    processor = DoSomethingBy_MyParent;
    processor(new MyParent());            //Error
}

在活动B中,确保将数据保存在 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", ""));

onBackPressed()

答案 1 :(得分:0)

您必须重写onBackPress()方法。在活动B中,必须将数据放入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();
}