恢复活动后,RecyclerView物品会丢失

时间:2019-01-24 18:06:52

标签: android android-studio arraylist android-recyclerview recyclerview-layout

在我的应用程序中,当用户单击“ 添加图像”按钮时,它允许用户从图库中选择图像并将其加载到“回收者视图”中。但是,当用户通过按“后退”按钮返回上一个活动并再次按下“ 添加图像”按钮时,先前选择的图像将从Recyclerview中丢失。我已经尝试过onSavedInstanceState(),但在我的情况下不起作用。我检查了各种StackOverflow解决方案,但没有任何帮助。

这是我的主要活动,称为RecorderActivity

public class RecorderActivity extends AppCompatActivity {
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.add_images) {
            Intent intent = new Intent(context,GridViewActivity.class);
            intent.putExtra("call","1");
            startActivity(intent);
        }
        else if(item.getItemId()==R.id.add_pdf_ppt) {
            Toast.makeText(context, "Under Development", Toast.LENGTH_SHORT).show();
        }
        else if(item.getItemId()==R.id.rearrange_items) {
            Intent i=new Intent(RecorderActivity.this,GridViewActivity.class);
            i.putExtra("call","2");
            startActivity(i);
        }
        return super.onOptionsItemSelected(item);
    }
}

在此处,当单击工具栏上的“ 添加图像”选项按钮时,它将打开GridViewActivity,用户可以在其中添加图库中的图像,但是当用户返回上一个活动(即RecorderActivity)并再次单击时,“ < strong>添加图像”按钮,先前选择的图像将从recyclerView中丢失。

这是我的GridViewActivity代码

这是更新的代码,在该代码中,我使用Gson将ArrayList保存到共享的首选项中,并且在onCreate()方法中,我从sharedPreferences中检索了ArrayList并将其设置为回收站视图,但是recyclerview仅显示证卡而不显示证卡内的图像。这就是问题!在sharedPreferences中,我使用一个count变量来指示sharedPreferences中的图像总数。

public class GridViewActivity extends AppCompatActivity {
    Context context=GridViewActivity.this;
    RecyclerView recyclerView;
    int PICK_IMAGE_MULTIPLE=1;
    static ArrayList<Images> arrayList;
    static ImagesAdapter imagesAdapter;
    AutoFitGridLayoutManager autoFitGridLayoutManager;
    SharedPref sharedPref;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_view);
        recyclerView=findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        autoFitGridLayoutManager=new AutoFitGridLayoutManager(context,250);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(autoFitGridLayoutManager);
        arrayList=new ArrayList<>();
        sharedPref=new SharedPref(context);
        if (sharedPref.getCount()==0) {
            Toast.makeText(context, "No images...", Toast.LENGTH_SHORT).show();
        }
        else {
            Gson gson=new Gson();
            String response=sharedPref.getImages();
            arrayList=gson.fromJson(response,new TypeToken<ArrayList<Images>>(){}.getType());
            Log.d("ROHIT", String.valueOf(arrayList.size()));
            imagesAdapter=new ImagesAdapter(context,arrayList);
            setRecyclerView();
        }
    }

    public void setRecyclerView() {
        ItemTouchHelper.Callback callback=new ItemMoveCallback(imagesAdapter);
        ItemTouchHelper touchHelper=new ItemTouchHelper(callback);
        touchHelper.attachToRecyclerView(recyclerView);
        recyclerView.setAdapter(imagesAdapter);
    }

     @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.add_imges_cam) {
            //open camera
        }
        else if(item.getItemId()==R.id.add_imges_gallery) {
            //open gallery to select images
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        int count=0;
        if(requestCode==PICK_IMAGE_MULTIPLE && resultCode==RESULT_OK) {
            String[] filePath = {MediaStore.Images.Media.DATA};

            if (data.getData() != null) {
                //if single image is selected
                Uri imageUri = data.getData();
                Cursor cursor = getContentResolver().query(imageUri, filePath, null, null, null);
                cursor.moveToFirst();
                arrayList.add(new Images(imageUri.toString()));
                cursor.close();
            } else {
                if (data.getClipData() != null) {
                    ClipData mClipData = data.getClipData();
                    for (int i = 0; i < mClipData.getItemCount(); i++) {
                        ClipData.Item item = mClipData.getItemAt(i);
                        Uri uri = item.getUri();
                        // Get the cursor
                        Cursor cursor = getContentResolver().query(uri, filePath, null, null, null);
                        // Move to first row
                        cursor.moveToFirst();
                        arrayList.add(new Images(uri.toString()));
                        count++;
                        cursor.close();
                    }
                }
            }
            imagesAdapter=new ImagesAdapter(context,arrayList);
            sharedPref.save(arrayList);
            Log.d("ROHIT","data saved arraylist"+arrayList.size());
            sharedPref.updateCount(count);
            Log.d("ROHIT","data saved");
            setRecyclerView();
        }
    }

}

这是SharedPref.java

public class SharedPref {
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    Context context;

    public SharedPref(Context context) {
        this.context=context;
        sharedPreferences=context.getSharedPreferences("Grid_images",Context.MODE_PRIVATE);
        editor=sharedPreferences.edit();
    }

    public void save(ArrayList<Images> arrayList) {
        Gson gson=new Gson();
        Object src;
        String json=gson.toJson(arrayList);
        editor.putString("grid_images",json);
        editor.apply();
        editor.commit();
    }

    public void updateCount(int i) {
        editor.putInt("images_count",i);
        editor.apply();
        editor.commit();
    }

    public int getCount() {
        return sharedPreferences.getInt("images_count",0);
    }

    public String getImages() {
        return sharedPreferences.getString("grid_images",null);
    }

这是Images.java类

public class Images implements Parcelable {
    private String image;

    public Images(String image) {
        this.image=image;
    }

    protected Images(Parcel in) {
        image = in.readString();
    }

    public static final Creator<Images> CREATOR = new Creator<Images>() {
        @Override
        public Images createFromParcel(Parcel in) {
            return new Images(in);
        }

        @Override
        public Images[] newArray(int size) {
            return new Images[size];
        }
    };

    public String getImage() {
        return image;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(String.valueOf(image));
    }
}

这是ImageAdapter类代码

public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.MyViewHolder> implements ItemMoveCallback.ItemTouchHelperContract {
    ArrayList<Images> images;
    Context context;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        View rowView;
        ImageButton bt_remove;
        public MyViewHolder(View itemView) {
            super(itemView);
            rowView=itemView;
            imageView=itemView.findViewById(R.id.imageview);
            bt_remove=itemView.findViewById(R.id.bt_delete);
        }
    }

    public ImagesAdapter(Context context,ArrayList<Images> images) {
        this.context=context;
        this.images=images;
    }

    public ImagesAdapter(Context context) {
        this.context=context;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.images_grid,parent,false);
        MyViewHolder myViewHolder=new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
        Images current_image=images.get(position);
        holder.imageView.setImageURI(Uri.parse(current_image.getImage()));

        holder.bt_remove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                images.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position,images.size());
            }
        });
    }

    @Override
    public int getItemCount() {
        return images.size();
    }

    @Override
    public void onRowMoved(int fromPosition, int toPosition) {
        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++) {
                Collections.swap(images, i, i + 1);
            }
        } else {
            for (int i = fromPosition; i > toPosition; i--) {
                Collections.swap(images, i, i - 1);
            }
        }
        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public void onRowSelected(MyViewHolder myViewHolder) {
        myViewHolder.rowView.setBackgroundColor(context.getResources().getColor(R.color.recycler_drag));
    }

    @Override
    public void onRowClear(MyViewHolder myViewHolder) {
        myViewHolder.rowView.setBackgroundColor(Color.WHITE);
    }
}

以下是输出:

从图库中选择4张图像后,它将显示在GridViewActivity的recyclerview中 enter image description here

但是在按下返回按钮并再次转到GridViewActivity之后,recyclerview显示如下 enter image description here

请不要将其标记为重复问题。 我对此进行了搜索,但是没有解决方案适合我。 请告诉我该怎么做才能解决此问题!

2 个答案:

答案 0 :(得分:0)

之所以发生这种情况,是因为每次从Gallery返回时都在创建一个新的ArrayList。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    arrayList=new ArrayList<>();
    ...
    // and then you are re-initializing your recycler view 
    imagesAdapter=new ImagesAdapter(context,arrayList);
    setRecyclerView();

因此,如果用户未从图库中选择任何图像,则在onActivityResult()内不会获得任何图像uri,但是在此之前,您将创建一个新的ArrayList并重新初始化您的recyclerview。

这就是为什么您的“回收者”视图中没有任何物品的原因。

将ArrayList保留为类成员变量,并继续基于onActivityResult()添加/删除数据。

答案 1 :(得分:0)

  

以此替换您的“活动”,然后尝试:

buttonTransition()