Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/218.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将数据保存在SharedReference中,尽管按下了后退按钮-Android Studio_Java_Android_Sharedpreferences - Fatal编程技术网

Java 将数据保存在SharedReference中,尽管按下了后退按钮-Android Studio

Java 将数据保存在SharedReference中,尽管按下了后退按钮-Android Studio,java,android,sharedpreferences,Java,Android,Sharedpreferences,正如我在问题中提到的,我有一些问题。我有两个活动,活动A和活动B。当我在活动A中输入一些数据时,我按下下一步按钮,它将重定向到活动B。在活动B中,我也输入一些数据。当我按下后退按钮时,活动A中的数据显示为我之前输入的数据。当我按下“下一步”按钮时,我在活动B中输入的数据丢失。下面是我的SharedReferencescode 活动A: public class NewSuggestion2 extends AppCompatActivity { private EditText etPrese

正如我在问题中提到的,我有一些问题。我有两个活动,活动A和活动B。当我在活动A中输入一些数据时,我按下下一步按钮,它将重定向到活动B。在活动B中,我也输入一些数据。当我按下后退按钮时,活动A中的数据显示为我之前输入的数据。当我按下“下一步”按钮时,我在活动B中输入的数据丢失。下面是我的
SharedReferences
code

活动A:

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


}
公共类NewsSuggestion扩展了AppCompative活动{

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);
}

}

为SharedRef中的礼物、细节和利益分配价值

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


您必须重写onBackPress()方法。在活动B中,有必要将数据放入SharedReferences

@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();
}

检查您的共享首选项是否在设备文件资源管理器中保存数据。您在下一次单击时将数据保存到共享性能,但从未在ActivityB中单击“下一步”。尝试将数据保存到TextChangedListener上的共享首选项,或在“下一步”中保存数据,并在“下一步”和“下一步”中同时按下两个按钮。在活动B中,也可以在“上一步”方法中调用共享首选项的数据存储。您可以按照此答案在sahredPreference中保存和检索数据:-执行此操作时请遵循此链接。问题仍然存在。我是否应该删除下一步中的SharedReference按钮?没有必要,当您打开活动B时,请确保您正在设置值(当前、当前、当前)。来自sahredpref。据我所知,您可以按共享偏好存储数据,但不能正确使用。你们能分享活动A和B的全部代码吗?让我明确一下这两个活动的生命周期。1.创建活动A。2.输入一些值3.按“下一步”将创建活动B。4.在活动B中按back键时,将显示活动A的相同实例。但当你再次按下“下一步”时,如果你用代码更新你的问题本身,就会创建活动B的新实例(这样就不会输入数据),更新答案也会更好。问题仍然存在。我是否应该删除“下一步”按钮中的SharedReference?
@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();
}