如何修复 Android 中将其他页面数据复制到 mainActivity 数据下方

how to fix Copy other pages data below mainActivity data in Android

我想为一个网站开发 Android 应用程序,我从 JSON 获取网站 post 并显示在 RecyclerView 中。我显示 titleimagedescriptioncategory MainActivity 我希望在单击 类别 时转到 categoryActivity 并显示此类别 posts!
我写了下面的代码,但是当转到 categoryActivity 并返回 MainActivity 时,我看到删除了 lasted post 并添加了 Category post 而不是 MainActivity last post!

例如:我的MainActivity是图片1:
当单击 post #2(来自类别 #2)并返回 MainActivity 时,在 MainActivity 中显示如下图:

复制下面的 post activity 并删除最后的 post!

适配器 class:(我使用一个适配器进行 2 项活动)

public class MainAdapter_loadMore extends RecyclerView.Adapter {

    private List<MainDataModel> mDateSet;
    private Context mContext;

    private final int VIEW_ITEM = 1;
    private final int VIEW_PROG = 0;

    // The minimum amount of items to have below your current scroll position
    // before loading more.
    private int visibleThreshold = 7;
    private int lastVisibleItem, totalItemCount;
    private boolean loading;
    private OnLoadMoreListener onLoadMoreListener;

    public MainAdapter_loadMore(Context context, RecyclerView recyclerView, List<MainDataModel> dataSet) {
        this.mContext = context;
        this.mDateSet = dataSet;

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {

            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
                    .getLayoutManager();
            recyclerView
                    .addOnScrollListener(new RecyclerView.OnScrollListener() {
                        @Override
                        public void onScrolled(RecyclerView recyclerView,
                                               int dx, int dy) {
                            super.onScrolled(recyclerView, dx, dy);
                            totalItemCount = linearLayoutManager.getItemCount();
                            lastVisibleItem = linearLayoutManager
                                    .findLastVisibleItemPosition();
                            if (!loading
                                    && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                                // End has been reached
                                // Do something
                                if (onLoadMoreListener != null) {
                                    onLoadMoreListener.onLoadMore();
                                }
                                loading = true;
                            }
                        }
                    });
        }
    }

    @Override
    public int getItemViewType(int position) {
        return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        RecyclerView.ViewHolder vh;
        if (viewType == VIEW_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.post_card_layout, parent, false);

            vh = new DataViewHolder(v);
        } else {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.progressbar_item, parent, false);

            vh = new ProgressViewHolder(v);
        }
        return vh;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

        if (holder instanceof DataViewHolder) {
            ((DataViewHolder) holder).main_post_title.setText(Html.fromHtml(mDateSet.get(position).getTitle()));

            Glide.with(mContext)
                    .load(mDateSet.get(position).getThumbnail())
                    .placeholder(R.drawable.post_image)
                    .crossFade()
                    .into(((DataViewHolder) holder).main_post_image);

            ((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));

            ((DataViewHolder) holder).main_dateTime.setText(Html.fromHtml(mDateSet.get(position).getDateTime()));

            ((DataViewHolder) holder).main_author.setText(Html.fromHtml(mDateSet.get(position).getAuthor()));

            ((DataViewHolder) holder).main_category.setText(Html.fromHtml(mDateSet.get(position).getCategory()));
            ((DataViewHolder) holder).main_category.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getPosition();
                    MainDataModel model = mDateSet.get(pos);
                    v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
                            .putExtra("categoryTitle", model.getCategory())
                            .putExtra("categoryID", model.getCategoryID()));
                }
            });

            ((DataViewHolder) holder).main_post_image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getPosition();
                    MainDataModel model = mDateSet.get(pos);
                    v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
                            .putExtra("title", model.getTitle())
                            .putExtra("image", model.getThumbnail())
                            .putExtra("content", model.getContent())
                            .putExtra("dateTime", model.getDateTime())
                            .putExtra("author", model.getAuthor())
                            .putExtra("category", model.getCategory()));

                }
            });

        } else {
            ((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
        }
    }

    public void setLoaded() {
        loading = false;
    }

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

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    public void remove(int position) {
        mDateSet.remove(position);
        notifyItemRemoved(position);
    }

    public void clear() {
        mDateSet.clear();
        notifyDataSetChanged();
    }


    public void add(List<MainDataModel> models) {
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public void update(List<MainDataModel> models) {
        mDateSet.clear();
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public class DataViewHolder extends RecyclerView.ViewHolder {

        private TextView main_post_title, main_post_content, main_dateTime, main_author, main_category;
        private ImageView main_post_image;

        public DataViewHolder(final View itemView) {
            super(itemView);

            main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
            main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
            main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
            main_dateTime = (TextView) itemView.findViewById(R.id.post_date_text);
            main_author = (TextView) itemView.findViewById(R.id.post_name_text);
            main_category = (TextView) itemView.findViewById(R.id.post_category_text);
        }
    }

    public static class ProgressViewHolder extends RecyclerView.ViewHolder {
        public AVLoadingIndicatorView progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
        }
    }
}

MainActivity AsyncTask 代码:

public class MainDataInfo_loadMore {
    private Context mContext;
    private String ServerAddress = ServerIP.getIP();

    public void getMainDataInfo_loadMore(Context context, int pageNumber) {
        mContext = context;
        new getInfo().execute(ServerAddress + "page=" + pageNumber);
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<MainDataModel> infoModels;

        @Override
        protected void onPreExecute() {
            //CustomProcessDialog.createAndShow(mContext);
            infoModels = new ArrayList<>();
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();

            String url = (String) params[0];
            Request request = new Request.Builder()
                    .url(url)
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();

            Response response;
            try {
                response = client.newCall(request).execute();
                ou_response = response.body().string();
                response.body().close();
                if (ou_response != null) {
                    try {
                        JSONObject postObj = new JSONObject(ou_response);
                        JSONArray postsArray = postObj.optJSONArray("posts");
                        infoModels = new ArrayList<>();

                        for (int i = 0; i <= infoModels.size(); i++) {
                            JSONObject postObject = (JSONObject) postsArray.get(i);
                            // Thumbnail
                            JSONObject images = postObject.optJSONObject("thumbnail_images");
                            JSONObject imagesPair = images.optJSONObject("medium");
                            // Author
                            JSONObject Author = postObject.optJSONObject("author");
                            // Category
                            JSONArray category = postObject.getJSONArray("categories");
                            for (int j = 0; j < category.length(); j++) {
                                JSONObject categoryObject = category.getJSONObject(j);

                                int id = postObject.getInt("id");
                                String title = postObject.getString("title");
                                String content = postObject.getString("content");
                                String dateTime = postObject.getString("date");
                                String thumbnail = imagesPair.getString("url");
                                String authorShow = Author.getString("name");
                                String categoryShow = categoryObject.getString("title");
                                String category_id = categoryObject.getString("id");

                                Log.d("Data", "Post ID: " + id);
                                Log.d("Data", "Post title: " + title);
                                Log.d("Data", "Post image: " + thumbnail);
                                Log.d("Data", "Post author: " + authorShow);
                                Log.d("Data", "Post category: " + categoryShow);
                                Log.d("Data", "Post category ID: " + category_id);
                                Log.d("Data", "---------------------------------");

                                //Use the title and id as per your requirement
                                infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, categoryShow, category_id, thumbnail));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String result) {
            //CustomProcessDialog.dissmis();
            if (result != null) {
                bus.post(infoModels);
            }
        }
    }
}

CategoryActivityAsyncTask:

public class CatDataInfo {
    private Context mContext;
    private String ServerAddress = ServerIP_cat.getCatIP();

    public void getCatDataInfo(Context context, String catID) {
        mContext = context;
        new getInfo().execute(ServerAddress + "id=" + catID);
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<MainDataModel> infoModels;

        @Override
        protected void onPreExecute() {
            CustomProcessDialog.createAndShow(mContext);
            infoModels = new ArrayList<>();
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();

            String url = (String) params[0];
            Request request = new Request.Builder()
                    .url(url)
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();

            Response response;
            try {
                response = client.newCall(request).execute();
                ou_response = response.body().string();
                response.body().close();
                if (ou_response != null) {
                    try {
                        JSONObject postObj = new JSONObject(ou_response);
                        JSONArray postsArray = postObj.optJSONArray("posts");
                        infoModels = new ArrayList<>();

                        for (int i = 0; i < postsArray.length(); i++) {
                            JSONObject postObject = (JSONObject) postsArray.get(i);
                            // Thumbnail
                            JSONObject images = postObject.optJSONObject("thumbnail_images");
                            JSONObject imagesPair = images.optJSONObject("medium");
                            // Author
                            JSONObject Author = postObject.optJSONObject("author");
                            // Category
                            JSONArray category = postObject.getJSONArray("categories");
                            for (int j = 0; j < category.length(); j++) {
                                JSONObject categoryObject = category.getJSONObject(j);

                                int id = postObject.getInt("id");
                                String title = postObject.getString("title");
                                String content = postObject.getString("content");
                                String dateTime = postObject.getString("date");
                                String thumbnail = imagesPair.getString("url");
                                String authorShow = Author.getString("name");
                                String categoryShow = categoryObject.getString("title");
                                String category_id = categoryObject.getString("id");

                                Log.d("CatData", "Cat Post ID: " + id);
                                Log.d("CatData", "Cat Post title: " + title);
                                Log.d("CatData", "Cat Post image: " + thumbnail);
                                Log.d("CatData", "Cat Post author: " + authorShow);
                                Log.d("CatData", "Cat Post category: " + categoryShow);
                                Log.d("CatData", "Cat Post category ID: " + category_id);
                                Log.d("CatData", "---------------------------------");

                                //Use the title and id as per your requirement
                                infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, categoryShow, category_id, thumbnail));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String result) {
            CustomProcessDialog.dissmis();
            if (result != null) {
                bus.post(infoModels);
            }
        }
    }
}

MainActivity class:

public class Main_page extends AppCompatActivity {

    private static final long RIPPLE_DURATION = 250;
    private Toolbar toolbar;
    private RelativeLayout root;
    private ImageView menu_image, toolbar_refresh;
    private RecyclerView main_recyclerView;
    private MainAdapter_loadMore mAdaper;
    private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
    protected Handler handler;
    private RelativeLayout loadLayout;
    private LinearLayoutManager mLayoutManager;
    private int pageCount = 1;
    String ServerAddress = ServerIP.getIP();
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {//go to the click action
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        // Initializing
        handler = new Handler();
        context = getApplicationContext();
        toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        mLayoutManager = new LinearLayoutManager(this);
        loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
        // Toolbar
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle(null);
        }
        // Load First Data
        LoadData();
        // Menu
        root = (RelativeLayout) findViewById(R.id.main_root);
        View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
        root.addView(guillotineMenu);
        menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
        new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
                .setStartDelay(RIPPLE_DURATION)
                .setActionBarViewForAnimation(toolbar)
                .setClosedOnStart(true)
                .build();
        // RecyclerView and setData
        main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
        main_recyclerView.setHasFixedSize(true);
        main_recyclerView.setLayoutManager(mLayoutManager);
        mAdaper = new MainAdapter_loadMore(this, main_recyclerView, dataModels);
        main_recyclerView.setAdapter(mAdaper);
        // Load More data
        mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                dataModels.add(null);
                mAdaper.notifyItemInserted(dataModels.size() - 1);
                LoadMoreData(pageCount);
            }
        });
    }

    @Subscribe
    public void onEvent(List<MainDataModel> mainInfoModels) {
        if (dataModels.size() > 0) {
            dataModels.remove(dataModels.size() - 1);
            mAdaper.notifyItemRemoved(dataModels.size());
            mAdaper.setLoaded();
        }

        mAdaper.add(mainInfoModels);
        mAdaper.notifyDataSetChanged();
        pageCount++;

        if (dataModels.isEmpty()) {
            main_recyclerView.setVisibility(View.GONE);
            loadLayout.setVisibility(View.VISIBLE);

        } else {
            main_recyclerView.setVisibility(View.VISIBLE);
            loadLayout.setVisibility(View.GONE);
        }
    }

    private void LoadData() {
        MainDataInfo dataInfo = new MainDataInfo();
        // here getMainDataInfo() should return the server response
        dataInfo.getMainDataInfo(this);
    }

    private void LoadMoreData(int pageNumber) {
        MainDataInfo_loadMore dataInfo_loadMore = new MainDataInfo_loadMore();
        // here getMainDataInfo() should return the server response
        dataInfo_loadMore.getMainDataInfo_loadMore(this, pageNumber);
    }
}

注意:请不要给我负分,我在google中搜索但没有找到我问题的答案。我是业余爱好者,我真的需要你的帮助!谢谢大家<3

尝试去除静电,这样

public static class ProgressViewHolder extends RecyclerView.ViewHolder {
        public AVLoadingIndicatorView progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
        }
    }

变成

public class ProgressViewHolder extends RecyclerView.ViewHolder {
        public AVLoadingIndicatorView progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
        }
    }