共享偏好设置在重新加载应用程序时删除数据

时间:2018-11-28 23:05:31

标签: android android-studio

我正在使用Android Studio创建我的第一个项目,我的目标是创建一个应用程序,您可以在该应用程序中从手机内存中加载照片并进行显示,以便人们看到。

我设法使它按我想要的方式工作,当我关闭应用程序然后重新打开它时,图库中的图片保持在应做的位置;但是,如果我关闭应用程序,则重新启动它并然后尝试添加一张新照片,它会覆盖画廊并删除我原来放的照片。有人对我如何解决此问题有任何想法吗?我在创建图像ArrayList时尝试过玩,但这没有帮助。

代码:

主要活动

public class MainActivity extends AppCompatActivity {

private static final int PERMISSION_REQUEST = 0;
private static final int RESULT_LOAD_IMAAGE = 1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";

ImageView imageView;
Button uploadButton;
Button savedPhotos;
List<String> images;
String imageCreated;

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

    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED){
        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
    }

    imageView = (ImageView) findViewById(R.id.imageView);
    uploadButton = (Button) findViewById(R.id.button);
    savedPhotos = (Button) findViewById(R.id.button2);

    SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();

    images = new ArrayList<>();

    uploadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAAGE);
            SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString(imageCreated, "Complete");
        }
    });

    savedPhotos.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openPage2();
        }
    });


}

public void openPage2()
{
    Intent intent = new Intent(this, SavedPhotos.class);
    startActivity(intent);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch(requestCode)
    {
        case PERMISSION_REQUEST:
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this, "Permission Not Granted", Toast.LENGTH_SHORT).show();
                finish();
            }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    switch(requestCode)
    {
        case RESULT_LOAD_IMAAGE:
            if(resultCode == RESULT_OK)
            {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();
                imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
                images.add(picturePath);
                StringBuilder stringBuilder = new StringBuilder();
                for(String i : images)
                {
                    stringBuilder.append(i);
                    stringBuilder.append(",");
                }
                SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString("images", stringBuilder.toString() );
                editor.commit();

            }
    }
}}

和保存的照片

public class SavedPhotos extends AppCompatActivity {

public static final String MyPREFERENCES = "MyPrefs" ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saved_photos);
    SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    String wordsString = sharedpreferences.getString("images", "");
    String[] itemWords = wordsString.split(",");
    List<String> items = new ArrayList<String>();
    LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
    for(int i = 0; i < itemWords.length; i++) {
        ImageView imageView = new ImageView(this);
        imageView.setId(i);
        imageView.setPadding(2, 2, 2, 2);
        imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground));
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        layout.addView(imageView);
        items.add(itemWords[i]);
        imageView.setImageBitmap(BitmapFactory.decodeFile(items.get(i)));
    }
}}

谢谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

在遇到一个精巧的库之前,我实际上遇到了同样的问题,不需要任何东西,并使我的代码看起来很漂亮,FastSave:https://github.com/yehiahd/FastSave-Android