如何从适配器获取itemList.size()或itemList到MainActivity

时间:2019-09-12 23:32:57

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

从代码片段中,我记录了一些调试点,并发现mImages.size()在不同的地方给出了不同的输出。 无论mImages.seize()的值如何,它总是在0中返回public ArrayList<Uri> getImageUris()。 ...对为什么...有帮助吗?

public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.ImageViewHolder> {

    private ArrayList<Image> mImages;
    private ArrayList<Uri> mImagesUri = new ArrayList<>();
    private Image mimage;
    private Uri uris;

    private static final String TAG = "ImagesAdapter";

    public ImagesAdapter(ArrayList<Image> images) {
        mImages = images;

        if (mImages == null)
            Log.d(TAG, "ImagesAdapter mImages = null");
    }

    @Override
    public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        return new ImageViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_pic_update, parent, false));

    }

    @Override
    public void onBindViewHolder(ImageViewHolder holder, final int position) {
        holder.bind(mImages.get(position));
        holder.cancel.setOnClickListener(view -> {
            int rpos = holder.getAdatpterpos();
            removeAt(rpos, mImages.get(position).getSource());

            Log.d(TAG, "imagesAdapter position = " + position);
        });
    }

    @Override
    public int getItemCount() {

        Log.d(TAG, "imagesAdapter getItemCount = " + mImages.size());
        return mImages.size();


    }


    public class ImageViewHolder extends RecyclerView.ViewHolder {

        protected ImageView imageView;
        private ImageButton cancel;

        public ImageViewHolder(View itemView) {
            super(itemView);

            imageView = itemView.findViewById(R.id.news_pic_update_details);
            cancel = itemView.findViewById(R.id.cancel_image);
        }

        public void bind(Image image) {

            imageView.setImageBitmap(image.getImage());
            imageView.setImageURI(image.getSource());

            Log.d(TAG, "imagesAdapter bind successful");

        }

        public int getAdatpterpos() {
            return getAdapterPosition();
        }

    }


    public void removeAt(int position, Uri path) {
        String mPath = null;
        File filepath;
        File mfilepath = null;

        try {
            mPath = path.toString();
            filepath = new File(mPath);
            mfilepath = new File(filepath.getAbsolutePath());
            mfilepath.delete();
        } catch (Exception e) {

            Log.e(TAG, "No Delete !!" + mPath + mfilepath);
            e.printStackTrace();
        }

        mImages.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, mImages.size());
        Log.d(TAG, "remove size = " + mImages.size());
        notifyDataSetChanged();

    }
        public ArrayList<Uri> getImageUris() {// here mImages.size is always 0

            if (!mImages.isEmpty()) {

                Log.d(TAG, "getImagesUris != Null \n mImages.size() = " + mImages.size());

                for (Image imageuri : mImages) {
                    uris = imageuri.getSource();

                    mImagesUri.add(uris);
                }
                Log.d(TAG, "getImagesUris != Null" + mImagesUri);

                return mImagesUri;


            } else

                Log.d(TAG, "getImagesUris = Null \n mImages.size() = " + mImages.size());

            return null;

        }
}

片段

    private ArrayList<Image> mImages = new ArrayList<>();
    private ImagesAdapter mImagesAdapter = new ImagesAdapter(mImages);
    private static final String TAG = "UploadNewsFragment";

    private Object[] mdata = new Object[2];
/**
<...>
*/
  private class loadImageTask extends AsyncTask<Object, Void, Bitmap> {

    Bitmap image = null;
    Uri uri, uriSource;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }
protected Bitmap doInBackground(Object... obj) {
            uri = (Uri) obj[1];
            uriSource = (Uri) obj[0];
            try {
                // Use the MediaStore to load the image.
                image = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "Error: " + e.getMessage() + "Could not open URI: "
                        + uri.toString());
            }

            return null;
        }


        protected void onPostExecute(Bitmap resultimage) {

            mImages.add(new Image(uriSource, image)); //here adds to the list
            mImagesAdapter.notifyDataSetChanged();
            mRecyclerView.smoothScrollToPosition(mImagesAdapter.getItemCount() - 1);

            Log.d(TAG, "OnPostExecute mImages.size() =" + mImages.size());// the mImages.s1ze() returns the correct value

        }}

MainActivity

    private ArrayList<Uri> newsImagesuri = new ArrayList<>();
        private ArrayList<String> uris = new ArrayList<>();
        String uriTostring;
        CW update;

        private ArrayList<Image> newsImages = new ArrayList<>();
        private ImagesAdapter mImagesAdapter = new ImagesAdapter(newsImages);

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

        mCompressor = new FileCompressor(this);


        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);

        // Called here..
        fab.setOnClickListener(view -> 
                upload_crime(view)
        );
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);

        //add this line to display menu1 when the activity is loaded
        displaySelectedScreen(R.id.nav_home);


        cwViewModel = ViewModelProviders.of(this)
                .get(CWViewModel.class);


    }
    /**
       <...>
    */

    public void upload_crime(View view) {
            EditText update_news = findViewById(R.id.update_news);
            String contents = update_news.getText().toString();
            Date now = Calendar.getInstance().getTime();

            newsImagesuri = mImagesAdapter.getImageUris(); // Here returns null from adapter
            if (newsImagesuri != null) {
                Log.d(TAG, "newsImagesuri != null" + newsImagesuri);
                for (Uri uri : newsImagesuri) {
                    uriTostring = uri.toString();
                    uris.add(uriTostring);
                    Log.d(TAG, "converted uris" + uris);
                }

                update = new CW(now, contents, uris);
                Log.d(TAG, "update contain uri" + uris);
            } else {

                Log.d(TAG, "newsImagesuri = null");

                update = new CW(now, contents, null);
            }

StackTrace

D/ImagesAdapter: imagesAdapter getItemCount = 0
    imagesAdapter getItemCount = 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
D/ImagesAdapter: getImagesUris = Null 
     mImages.size() = 0
D/MainActivity: newsImagesuri = null
D/TextView: setTypeface with style : 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1

show : false
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@27bdf29 time:17894100
D/ImagesAdapter: imagesAdapter getItemCount = 1
D/UploadNewsFragment: OnPostExecute mImages.size() =1
D/ImagesAdapter: imagesAdapter getItemCount = 1
    imagesAdapter getItemCount = 1
    imagesAdapter getItemCount = 1
I/BitmapFactory: DecodeImagePath(decodeResourceStream3) : value is null. res : null
D/ImagesAdapter: imagesAdapter bind successful
    imagesAdapter getItemCount = 1
    imagesAdapter getItemCount = 1
    imagesAdapter getItemCount = 1
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
D/ImagesAdapter: getImagesUris = Null 
     mImages.size() = 0
D/MainActivity: newsImagesuri = null
D/TextView: setTypeface with style : 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
V/ActivityThread: updateVisibility : ActivityRecord{8f2490 token=android.os.BinderProxy@27bdf29 {com.x.unncrimewatch/com.x.unncrimewatch.MainActivity}} show : true
V/ActivityThread: updateVisibility : ActivityRecord{8f2490 token=android.os.BinderProxy@27bdf29 {com.x.unncrimewatch/com.x.unncrimewatch.MainActivity}} show : false

2 个答案:

答案 0 :(得分:1)

我想我知道为什么。 MainActivityFragment中有2个单独的适配器,带有2个不同的图像列表。

您在Fragment中的列表中添加了项目,但MainActivity中的列表从未更新。

因此,当您在MainActivity中调用upload_crime()时,图像列表的大小始终为0。

您只能在一个地方与适配器互动,最好是片段

答案 1 :(得分:0)

要将信息从Array传递给其他Array时,您做错了。您无法执行此操作-> mImages = images;

您可能会问为什么?...当您这样做时,mImages等于images,换句话说,如果您清除了图像images.clear )。. mImages 也将被清除。

您需要做的 mImages.addAll(images); ,这样,两者将具有相同的data,但两者换句话说,如果您清除其中一个数组,则将有所不同。另一个数组将不会被清除。

请确保在您执行此操作的每个地方都执行我告诉过您的内容array = array

希望它能帮助您