如何在Android中加载片段中的json数据

时间:2016-06-06 10:30:09

标签: android android-fragments android-asynctask android-json

我想在我的fragments中显示3 Activity,并在任何json中加载来自 fragments 的数据!我希望将每个json数据显示为一个片段,但在我的应用程序中显示所有片段中的所有数据! 例如:我想将文章音乐数据显示文章数据转换为音乐片段fragment s中的所有数据(文章,音乐,视频)! 在我的应用程序中,我使用 EventBus 来发送数据,并使用一个 DataModel 来保存json数据。

片段1:

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;

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

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

        context = getContext();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        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(List<DataModel> mainInfoModels) {
/*        if (dataModels.size() > 0) {
            dataModels.remove(dataModels.size() - 1);
            mAdapter.notifyItemRemoved(dataModels.size());
            //mAdapter.setLoaded();
        }*/

        mAdapter.add(mainInfoModels);
        mAdapter.notifyDataSetChanged();
    }

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

片段2:

public class paid_fragment extends Fragment {

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

    private Context context;

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

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

        context = getContext();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        LoadData();

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

        return view;
    }

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

        mAdapter.add(mainInfoModels);
        mAdapter.notifyDataSetChanged();
    }

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

片段1的AsyncTask代码:

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

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

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<DataModel> 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(ServerAddress + "limit=10")
                    .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("result");
                        infoModels = new ArrayList<>();

                        for (int i = 0; i <= infoModels.size(); 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("description");
                            String image = postObject.getString("image");
                            String category = postObject.getString("categoryName");
                            String date = postObject.getString("publishDate");

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

                            //Use the title and id as per your requirement
                            infoModels.add(new DataModel(id, title, description, category, date, 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();
            if (result != null) {
                bus.post(infoModels);
            } else {
                Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

片段2的AsyncTask代码:

public class paidDataInfo {
    private Context mContext;
    private String ServerAddress = paidServer_IP.getPaidIP();

    public void getPaidDataInfo(Context context) {
        mContext = context;
        new getInfo().execute(ServerAddress + "limit=10");
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<DataModel> 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(ServerAddress + "limit=10")
                    .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("result");
                        infoModels = new ArrayList<>();

                        for (int i = 0; i <= infoModels.size(); 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("description");
                            String image = postObject.getString("image");
                            String category = postObject.getString("categoryName");
                            String date = postObject.getString("publishDate");

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

                            //Use the title and id as per your requirement
                            infoModels.add(new DataModel(id, title, description, category, date, 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();
            if (result != null) {
                bus.post(infoModels);
            } else {
                Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

for (int i = 0; i <= infoModels.size(); i++)

替换为

for (int i = 0; i <= postsArray.length(); i++)

同时签署ArrayList infoModels一次

<强> private List<DataModel> infoModels = new ArrayList<>();

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

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

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

        @Override
        protected void onPreExecute() {
            CustomProcessDialog.createAndShow(mContext);
        }

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

            //String url = (String) params[0];
            Request request = new Request.Builder()
                    .url(ServerAddress + "limit=10")
                    .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("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("description");
                            String image = postObject.getString("image");
                            String category = postObject.getString("categoryName");
                            String date = postObject.getString("publishDate");

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

                            //Use the title and id as per your requirement
                            infoModels.add(new DataModel(id, title, description, category, date, 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();
            if (result != null) {
                bus.post(infoModels);
            } else {
                Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

答案 1 :(得分:1)

您总是为每个片段发布相同的事件,然后您将获得所有片段中的所有项目。 发布EventBus时需要上课:

public class MyEvent {
private String fragmentTag ;
private ArrayList<DataModel> infoModels ;

public MyEvent (String tag,ArrayList<DataModel> models){
    this.fragmentTag = tag;
    this.infoModels = models;
}

}

然后发布如下:

bus.post(new MyEvent ("forfragment1",infoModels) );

然后在你的Fragment1:

@Subscribe
public void onEvent(MyEvent event) {
    if(event.fragmentTag.equals("forfragment1"))
    {
       //populate your view , do something
    }
}

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