如何在片段中刷新recyclerview的数据?

时间:2019-05-02 04:11:33

标签: android android-fragments android-recyclerview swiperefreshlayout

我在HomePageActivity中发布API并获取Data,然后使用参数将数据传递到NewFragment并显示。

现在,我想要的是,当NewFragment中的用户使用swiperefresh时,NewFragment将在HomePageActivty中调用该函数,并且该函数将清除数据并调用post API以获取新数据并写入参数以发送到NewFragment,然后NewFragment将重新加载新数据并显示它。

我可以在HomePageActivty中调用该函数并调用post API,但是当我要将数据重新加载到NewFragment时,它无法显示!

如何解决此问题?

这是我的HomePageActivity

public class HomePageActivity extends AppCompatActivity {

    public static String TAG = "HomePageActivity";

    private postSectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    public static String[] HomeToNew_user_icon, HomeToNew_user_name, HomeToNew_post_time, HomeToNew_post_text, HomeToNew_post_img, HomeToNew_post_likes, HomeToNew_post_comments, HomeToNew_post_pid = null;
    public static int NewArrayLength;

    private static String token;

    public static Context context;

    @SuppressLint("ResourceType")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);

        context = HomePageActivity.this;

        mSectionsPagerAdapter = new postSectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        token = MainActivity.memoryToken;
        Toast.makeText(this,"Token in HomePage: " + token, Toast.LENGTH_SHORT).show();

        new JSONTask_New(HomePageActivity.this, token, "0", block).execute("api");

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

        tabLayout.getTabAt(0).setText(R.string.New_Tab);
        tabLayout.getTabAt(1).setText(R.string.Hot_Tab);

    }

    public static void refresh_New_Data(){
        initData();
        reLoad();
    }

    public static void initData(){
        HomeToNew_user_icon = null;
        HomeToNew_user_name = null;
        HomeToNew_post_time = null;
        HomeToNew_post_text = null;
        HomeToNew_post_img = null;
        HomeToNew_post_likes = null;
        HomeToNew_post_comments = null;
        HomeToNew_post_pid = null;
        NewArrayLength = 0;
    }

    public static void reLoad(){
        new JSONTask_New(context, token, "0", "1").execute("http://52.69.75.199/cp/posts/");
        Log.e(TAG, "REFRESH New(HomePage) ApiCall posts!");
    }

    public class postSectionsPagerAdapter extends FragmentPagerAdapter {

        public postSectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    return new NewFragment();
                case 1:
                    return new HotFragment();
            }
            return null;
        }
    }

    // Post New (GET).
    public static class JSONTask_New extends AsyncTask<String, String, String> {

        private Context context;
        private String token;
        private String type;
        private String block;

        public JSONTask_New(Context context, String token, String type, String block) {
            this.context = context;
            this.token = token;
            this.type = type;
            this.block = block;
        }

        @Override
        protected String doInBackground(String... params) {

            try {

                String SERVER_WS_URL = params[0];

                LinkedHashMap<String, String> parameter = new LinkedHashMap<>();
                parameter.put("token", token);
                parameter.put("type",  "0");
                parameter.put("block",  "0");

                return ApiCall.getWebserviceCall(SERVER_WS_URL, parameter); 

            } catch (Exception e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            try {

                if (result != null) {

                    JSONObject jsonObject = new JSONObject(result.toString());

                    String code = jsonObject.getString("code");
                    String desc = jsonObject.getString("desc");

                    if (Integer.valueOf(code) == 1) {

                        JSONArray jsonArray = jsonObject.getJSONArray("list");

                        HomeToNew_user_icon = new String[jsonArray.length()];
                        HomeToNew_user_name = new String[jsonArray.length()];
                        HomeToNew_post_time = new String[jsonArray.length()];
                        HomeToNew_post_text = new String[jsonArray.length()];
                        HomeToNew_post_img = new String[jsonArray.length()];
                        HomeToNew_post_likes = new String[jsonArray.length()];
                        HomeToNew_post_pid = new String[jsonArray.length()];
                        HomeToNew_post_comments = new String[jsonArray.length()];

                        NewArrayLength = jsonArray.length();

                        for(int i = 0; i < jsonArray.length(); i++){
                            JSONObject jsonObject_item = jsonArray.getJSONObject(i);

                            HomeToNew_user_icon[i] = jsonObject_item.getString("head");
                            HomeToNew_user_name[i] = jsonObject_item.getString("name");
                            HomeToNew_post_time[i] = jsonObject_item.getString("created");
                            HomeToNew_post_text[i] = jsonObject_item.getString("txt");
                            HomeToNew_post_img[i] = jsonObject_item.getString("img");
                            HomeToNew_post_likes[i] = jsonObject_item.getString("gd");
                            HomeToNew_post_comments[i] = jsonObject_item.getString("co");
                            HomeToNew_post_pid[i] = jsonObject_item.getString("pid");
                        }
                    } else {
                        Toast.makeText(context, "NewPost API code: " + code + ", desc: " + desc, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(context, "NewPost data null!", Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

这是我的NewFragment

public class NewFragment extends Fragment {

    public static String TAG = "NewFragment";

    private RecyclerView postcardRecycler;
    private ArrayList<PostCard> post_data = new ArrayList<>();
    private PostCardImageAdapter adapter;

    private String[] user_icon, user_name, post_time, post_text, post_img, post_likes, post_comments, post_pid = null;

    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.new_layout, container, false);
        user_icon = HomePageActivity.HomeToNew_user_icon;
        user_name = HomePageActivity.HomeToNew_user_name;
        post_time = HomePageActivity.HomeToNew_post_time;
        post_text = HomePageActivity.HomeToNew_post_text;
        post_img = HomePageActivity.HomeToNew_post_img;
        post_likes = HomePageActivity.HomeToNew_post_likes;
        post_comments = HomePageActivity.HomeToNew_post_comments;
        post_pid = HomePageActivity.HomeToNew_post_pid;

        postcardRecycler = view.findViewById(R.id.new_layout_recycler);

        for(int i = 0; i < HomePageActivity.NewArrayLength; i++){
            post_data.add(new PostCard(user_icon[i], user_name[i], post_time[i], post_text[i], post_img[i], post_likes[i], post_comments[i], post_pid[i]));
        }

        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        postcardRecycler.setLayoutManager(layoutManager);

        adapter = new PostCardImageAdapter(getActivity(), post_data);
        postcardRecycler.setAdapter(adapter);

        swipeRefreshLayout = view.findViewById(R.id.new_layout_swipe_refresh);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onRefresh() {
                Log.e(TAG, "Enter New onRefresh!");
                HomePageActivity.refresh_New_Data();
                NewFragment fragment = new NewFragment();
                getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
                swipeRefreshLayout.setRefreshing(false);
            }

        });

        return view;
    }

}

这是我的new_layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/new_layout_swipe_refresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/new_layout_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical" />

</android.support.v4.widget.SwipeRefreshLayout>

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

方法 FragmentTransaction#replace 需要 containerViewId ,但不需要layoutId https://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html#replace_1 这样,当您调用 replace(R.layout.new_layout,fragment)时,将引发异常

解决方案:您可以将newFragment存储在HomePageActivity中,并在NewFragment中添加方法inflateData。成功获取数据后,将调用newFragment.inflateData()