如何在Android上的片段中显示JSON数据

时间:2016-05-31 11:21:23

标签: android json android-fragments

我希望在 fragment 中插入3 MainActivity,然后在fragments中轻扫该fragment的数据! 对于show网站帖子,我使用 Json ,我写下面的代码,当运行应用程序时没有向我显示fragments中的任何帖子只是在{{}中显示此消息 1}}:

logCat

片段代码:

05-31 15:40:22.303 18219-18219/com.razemovafaghiat.tellfa.android D/LGMtpDatabaseJNI: register_android_mtp_LGMtpDatabase
05-31 15:40:25.612 18219-18304/com.razemovafaghiat.tellfa.android W/System.err:     at com.razemovafaghiat.tellfa.android.AccessLayer.freeDataInfo$getInfo.doInBackground(freeDataInfo.java:75)
05-31 15:40:25.612 18219-18304/com.razemovafaghiat.tellfa.android W/System.err:     at com.razemovafaghiat.tellfa.android.AccessLayer.freeDataInfo$getInfo.doInBackground(freeDataInfo.java:38)

适配器代码:

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 = getActivity();

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

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

        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);
    }

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

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

AsyncTask代码(freeDataInfo):

public class free_recycler_adapter extends RecyclerView.Adapter<free_recycler_adapter.ViewHolder> {
    private static String[] mDataset;
    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(context).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, 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()));
        Glide.with(context)
                .load(mDateSet.get(position).getImage())
                .placeholder(R.drawable.ic_content_info_cat)
                .crossFade()
                .into(viewHolder.free_avatarImage);
        viewHolder.free_descText.setText(Html.fromHtml(mDateSet.get(position).getDescription()));

    }

    // 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);

            itemLayoutView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(v.getContext(), ContentPage.class);
                    v.getContext().startActivity(intent);
                }
            });
        }
    }
}

对于节目数据,我使用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"); String title = postObject.getString("title"); String description = postObject.getString("content"); 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", "---------------------------------"); //Use the title and id as per your requirement infoModels.add(new DataModel(id, title, description, image, category, date)); } } 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); } else { Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show(); } } } }

如何解决此问题并在片段中显示网站数据?

1 个答案:

答案 0 :(得分:1)

您必须检查Context变量。在片段中,您必须在onCreateView本身的 Fragment 方法中定义和设置上下文变量,而不是调用者活动。

context=getActivity();方法中的

onCreateView