如何在Android

时间:2016-08-08 05:52:23

标签: android android-fragments android-asynctask android-event

我想在3 fragments中使用 json 显示网站数据!在 TAB 之间滑动时不重复数据。但是当点击 TAB 时,再次复制以前的数据!
要将数据从 AsyncTask 发送到碎片,请使用 EventBus 组件。
片段代码:

public class free_fragment extends Fragment {

    private RecyclerView mRecyclerView;
    private free_recycler_adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<DataModel> dataModels = new ArrayList<DataModel>();

    private Context context;
    private boolean isDataFetched;
    private boolean mIsVisibleToUser;
    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_free_layout, container, false);

        context = getContext();

        if (mIsVisibleToUser) {
            LoadData();
        }

        ///----- RecyclerView -----
        mRecyclerView = (RecyclerView) view.findViewById(R.id.pdf_RecyclerView);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new free_recycler_adapter(context, dataModels);
        mRecyclerView.setAdapter(mAdapter);


        return view;
    }

    @Subscribe
    public void onEvent(MyEvent event) {
        List<DataModel> dataModels = event.getInfoModels();
/*        if (dataModels.size() > 0) {
            dataModels.remove(dataModels.size() - 1);
            mAdapter.notifyItemRemoved(dataModels.size());
            //mAdapter.setLoaded();
        }*/
        if (event.fragmentTag.equals("forfragment1")) {
            mAdapter.add(dataModels);
            isDataFetched = true;
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        mIsVisibleToUser = isVisibleToUser;
        if (isVisibleToUser && !isDataFetched && getContext() != null) {
            context = getContext();
            LoadData(); //Remove this call from onCreateView
        }
    }

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

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }
}

AsyncTask代码:

public class freeDataInfo {
    private Context mContext;
    private String ServerAddress = freeServer_IP.getFreeIP();
    private DiskLruDataCache mDiskLruCache;

    public void getFreeDataInfo(Context context) {
        mContext = context;
        this.mDiskLruCache=new DiskLruDataCache(context);
        //new getInfo().execute(ServerAddress + "limit=10");
        new getInfo().execute(ServerAddress);
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<DataModel> infoModels = new ArrayList<>();
        private ProgressDialog dialog;

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

            // Initiate Progress
            dialog = new ProgressDialog(mContext);
            this.dialog.setMessage("شکیبا باشید...");
            this.dialog.show();

            infoModels.clear();
        }

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

            //String url = (String) params[0];
            Request request = new Request.Builder()
                    //.url(ServerAddress + "limit=10")
                    .url(ServerAddress)
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();

            Response response;
            try {
                if(CheckInternet.isConnected(mContext)) {
                    response = client.newCall(request).execute();
                    ou_response = response.body().string();
                    if (ou_response != null) {
                        mDiskLruCache.cacheToDisk(ServerAddress, ou_response);
                    }
                    response.body().close();
                }
                else{
                    ou_response=mDiskLruCache.fetchFromDiskCache(ServerAddress);
                }
                if (ou_response != null) {
                    try {
                        JSONObject postObj = new JSONObject(ou_response);
                        JSONArray postsArray = postObj.optJSONArray("result");

                        for (int i = 0; i <= postsArray.length(); i++) {
                            JSONObject postObject = (JSONObject) postsArray.get(i);


                            int id = postObject.getInt("id");
                            Log.d("id", String.valueOf(id));
                            String title = postObject.getString("title");
                            String description = postObject.getString("full_description");
                            String image = postObject.getString("image");
                            String category = postObject.getString("categoryName");
                            String date = postObject.getString("date");
                            String url = postObject.getString("url");

                            Log.d("Data", "Post ID: " + id);
                            Log.d("Data", "Post title: " + title);
                            Log.d("Data", "Post image: " + image);
                            Log.d("Data", "Post url: " + url);
                            Log.d("Data", "---------------------------------");

                            //Use the title and id as per your requirement
                            infoModels.add(new DataModel(id, title, description, category, date, url, image));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("error", String.valueOf(e));
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("error2", String.valueOf(e));
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String result) {
            //CustomProcessDialog.dissmis();

            //Stop Progress
            if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if (result != null) {
                bus.post(new MyEvent("forfragment1", infoModels));
            } else {
                Toast.makeText(mContext, "Check Internet", Toast.LENGTH_LONG).show();

            }
        }
    }
}

适配器代码:

public class free_recycler_adapter extends RecyclerView.Adapter<free_recycler_adapter.ViewHolder> {
    private List<DataModel> mDateSet;
    private Context context;

    // Provide a suitable constructor (depends on the kind of dataset)
    public free_recycler_adapter(Context context, List<DataModel> dataSet) {
        this.context = context;
        this.mDateSet = dataSet;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public free_recycler_adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.free_card_layout, parent, false);

        // create ViewHolder
        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // - get data from your itemsData at this position
        // - replace the contents of the view with that itemsData

        viewHolder.free_titleText.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
        viewHolder.free_titleText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
                        .putExtra("title", mDateSet.get(position).getTitle())
                        .putExtra("desc", mDateSet.get(position).getDescription())
                        .putExtra("image", mDateSet.get(position).getImage())
                        .putExtra("url", mDateSet.get(position).getUrl())
                        .putExtra("category", mDateSet.get(position).getCategory())
                        .putExtra("date", mDateSet.get(position).getDate()));
            }
        });

        Glide.with(context)
                .load(mDateSet.get(position).getImage())
                .placeholder(R.drawable.ic_download_image)
                .crossFade()
                .into(viewHolder.free_avatarImage);
        viewHolder.free_avatarImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
                        .putExtra("title", mDateSet.get(position).getTitle())
                        .putExtra("desc", mDateSet.get(position).getDescription())
                        .putExtra("image", mDateSet.get(position).getImage())
                        .putExtra("url", mDateSet.get(position).getUrl())
                        .putExtra("category", mDateSet.get(position).getCategory())
                        .putExtra("date", mDateSet.get(position).getDate()));
            }
        });

        viewHolder.free_descText.setText(Html.fromHtml(mDateSet.get(position).getDescription()));
        viewHolder.free_descText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
                        .putExtra("title", mDateSet.get(position).getTitle())
                        .putExtra("desc", mDateSet.get(position).getDescription())
                        .putExtra("image", mDateSet.get(position).getImage())
                        .putExtra("url", mDateSet.get(position).getUrl())
                        .putExtra("category", mDateSet.get(position).getCategory())
                        .putExtra("date", mDateSet.get(position).getDate()));
            }
        });

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDateSet.size();
    }

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

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

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

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

    // inner class to hold a reference to each item of RecyclerView
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView free_titleText, free_descText;
        public ImageView free_avatarImage;

        public ViewHolder(View itemLayoutView) {
            super(itemLayoutView);

            free_titleText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_title);
            free_descText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_content);
            free_avatarImage = (ImageView) itemLayoutView.findViewById(R.id.pdf_card_image);

        }
    }
}

主要活动代码:

public class Main_Page extends AppCompatActivity {

    private CollapsingToolbarLayout mCollapsingToolbarLayout;
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    private DrawerLayout mDrawer;
    private NavigationView nvDrawer;
    private ImageView menuImage;

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

        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                .setDefaultFontPath("fonts/iransans.ttf")
                .setFontAttrId(R.attr.fontPath)
                .build());

        mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
        //mCollapsingToolbarLayout.setTitle(getResources().getString(R.string.app_name));

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();

        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        nvDrawer = (NavigationView) findViewById(R.id.navigation_drawer);
        menuImage = (ImageView) findViewById(R.id.DrawableMenu_image);
        menuImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawer.openDrawer(GravityCompat.END);
            }
        });

    }

    /**
     * Adding custom view to tab
     */
    private void setupTabIcons() {

        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText(R.string.free_fragment_title);
        tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_download_image, 0, 0);
        tabLayout.getTabAt(0).setCustomView(tabOne);

        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabTwo.setText(R.string.paid_fragment_title);
        tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_paid_download_image, 0, 0);
        tabLayout.getTabAt(1).setCustomView(tabTwo);

        TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabThree.setText(R.string.pdf_fragment_title);
        tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_pdf_icon, 0, 0);
        tabLayout.getTabAt(2).setCustomView(tabThree);
    }

    /**
     * Adding fragments to ViewPager
     *
     * @param viewPager
     */
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new free_fragment(), "رایگان ها");
        adapter.addFrag(new paid_fragment(), "پرداختی ها");
        adapter.addFrag(new pdf_fragment(), "مقالات");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    @Override
    public void onBackPressed() {
        if (mDrawer.isDrawerOpen(GravityCompat.END)) {
            mDrawer.closeDrawers();
        } else
            super.onBackPressed();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

}

如何点击 TabLayout 来解决此问题而不是重复数据? 我很业余,我真的需要这个帮助,请帮助我。谢谢所有&lt; 3

2 个答案:

答案 0 :(得分:0)

检查注释的代码:它导致每次都向适配器添加dataModels。

@Subscribe
public void onEvent(MyEvent event) {
       List<DataModel> dataModels = event.getInfoModels();

       if (event.fragmentTag.equals("forfragment1")) {
                //mAdapter.add(dataModels);
                isDataFetched = true;
                mAdapter.notifyDataSetChanged();
       }
}
  • 在你的适配器中,在add()方法中,你要重新将数据添加到列表中,这是不必要的,调用notifyDataSetChanged会自动暗示原始数据已被更改的适配器。

  • 只需在适配器上调用notifyDataSetChanged即可刷新更新后的数据。希望能帮助到你。

答案 1 :(得分:-1)

尝试

viewPager.setOffscreenPageLimit(3);