在Android中解析JSON新闻

时间:2016-08-20 02:40:23

标签: android json api parsing

我正在尝试显示从json数据源收到的新闻。但是,当我尝试解析数据时,我收到错误。

json数据看起来像这样:

click here to view

这是我为解析编写的类:

public class FragmentUniversityNews extends Fragment {
private String TAG = FragmentUniversityNews.class.getSimpleName();
private static final String endpoint = "https://api.myjson.com/bins/18smd";
private static final String endpoint_final = "http://srm-news-bot.herokuapp.com";
private SwipeRefreshLayout swipeRefreshLayout;
private SimpleStringRecyclerViewAdapter mAdapter;
private JsonObjectRequest req;
String[] titles = new String[15];
String[] snips = new String[15];
String[] links = new String[15];

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

    View rootView = inflater.inflate(R.layout.fragment_university_news, container, false);
    //((ActivityMain) getActivity()).showFloatingActionButton();
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view_university);
    swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
    swipeRefreshLayout.setColorSchemeResources(R.color.red500, R.color.black, R.color.google_blue_900);

    mAdapter = new SimpleStringRecyclerViewAdapter(getContext(), titles, snips, links);

    // Calling another function which has the details
    setupRecyclerView(recyclerView);

    // Make it look like something is happening
    swipeRefreshLayout.setRefreshing(true);
    // Make the request!
    makeJSONRequest();

    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            // onRefresh action here
            swipeRefreshLayout.setRefreshing(true);
            makeJSONRequest();
        }
    });

    return rootView;
}

private void setupRecyclerView(RecyclerView recyclerView) {
    recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(mAdapter);
}

public void makeJSONRequest() {
    req = new JsonObjectRequest(endpoint_final,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    // Getting JSON Array node
                    JSONArray newsItems = response.getJSONArray("newsItems");
                    // UI
                    try {
                        for (int j = 0; j < newsItems.length(); j++) {
                            JSONObject newsItem = newsItems.getJSONObject(j);
                            titles[j] = newsItem.getString("title");
                            snips[j] = newsItem.getString("snip");
                            links[j] = newsItem.getString("link");
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    } catch (JSONException e) {
                        Log.e(TAG, "Json parsing error: " + e.getMessage());
                        Toast.makeText(getContext(), "JSON Parsing error", Toast.LENGTH_LONG).show();
                    } mAdapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Error: " + error.getMessage());
            Toast.makeText(getContext(), "Error Receiving News", Toast.LENGTH_LONG).show();
        }
    });

    // Adding request to request queue
    InitializeVolley.getInstance().addToRequestQueue(req);
}

public static class SimpleStringRecyclerViewAdapter extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {
    private String[] mTitles, mSnips, mLinks;
    private Context mContext;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mTextViewTitle, mTextViewSnip;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mTextViewTitle = (TextView) view.findViewById(R.id.univ_news_title);
            mTextViewSnip = (TextView) view.findViewById(R.id.univ_news_snip);
        }
    }

    // Constructor
    public SimpleStringRecyclerViewAdapter(Context context, String[] Titles, String[] Snips, String[] Links) {
        mContext = context;
        mTitles = Titles;
        mSnips = Snips;
        mLinks = Links;
    }

    public String getTitleAt(int position) {
        return mTitles[position];
    }

    public String getSnipAt(int position) {
        return mSnips[position];
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view_univ, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.mTextViewTitle.setText(getTitleAt(position));
        holder.mTextViewSnip.setText(getSnipAt(position));
        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //startScan();
                Context context = v.getContext();
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mLinks[holder.getAdapterPosition()]));
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mTitles.length;
    }   
   }    
}   

我在Android Studio中遇到的错误位于“JSONArray newsItems = response.getJSONArray(”newsItems“);”,

这是说

Unhandled exception:org.json.JSONException

当我在“try”块中移动JSONArray newsItems = response.getJSONArray("newsItems");时,它会显示

`Cannot resolve constructor 'JsonObjectRequest(java.lang.String, anonymous     com.android.volley.Response.Listener<org.json.JSONObject>, anonymous com.android.volley.Response.ErrorListener)'`

2 个答案:

答案 0 :(得分:0)

仅从代码中隔离解析部分我无法重现错误,这是我的代码:

String jsonStr = "";//TODO insert JSON sample from link
JSONObject jsonObj = null;
try {
    jsonObj = new JSONObject(jsonStr);
    JSONArray newsItems = jsonObj.getJSONArray("newsItems");
    for (int j = 0; j < newsItems.length(); j++) {
        JSONObject newsItem = newsItems.getJSONObject(j);
        Log.d(TAG,
            "Title: " +newsItem.getString("title") +
            "\nSnip: " + newsItem.getString("snip") +
            "\nLink: " +newsItem.getString("link")
        );
    }
} catch (JSONException e) {
    e.printStackTrace();
}

直接以JSONObject或与JSON解析无关的任何内容检索内容时出错。 为了帮助你进一步发展,如Kris Roofe已经提到的那样,有一个错误日志会很棒。

答案 1 :(得分:0)

我通过添加&#34; null&#34;解决了我的问题。在JSONObjectRequest函数中。我不明白为什么。

public void makeJSONRequest() { req = new JsonObjectRequest(endpoint_final, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString());