volley错误org.json.JSONException:没有值

时间:2017-02-25 09:35:15

标签: android json android-fragments android-volley

我正试图从json中提取新闻。 但我正在片段而不是活动。

我的代码没有错误,但是当我运行应用程序时,我收到错误" org.json.JSONException:没有值为newsItem"在控制台和logcat中。

这是我的fragment.java

    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.Volley;
    import com.comp.app.news.R;
    import com.comp.app.news.activities.NewsItems;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.List;


    public class NewsFragment extends Fragment {

private List<NewsItems> newsFeed = new ArrayList<>();

public NewsFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_news, container, false);

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("News");

    RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());

    JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
            "https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                    JSONArray NewsItems = response.getJSONArray("newsItems");

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

                            JSONObject temp = NewsItems.getJSONObject(i);

                            String title = temp.getString("title");
                            String description = temp.getString("description");
                            String url = temp.getString("url");
                            String urlToImage = temp.getString("urlToImage");

                            newsFeed.add(new NewsItems(title, description, url, urlToImage));
                        }
                    } catch (JSONException e){
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    queue.add(newsReq);

    ArrayAdapter<NewsItems> adapter = new customAdapter();

    ListView news_list =(ListView) (getActivity().findViewById(R.id.newsList));
    news_list.setAdapter(adapter);
}

private class customAdapter extends ArrayAdapter<NewsItems>{
    customAdapter() {
        super(getActivity(), R.layout.custom_list, newsFeed);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {

        if (convertView == null){
            convertView = getActivity().getLayoutInflater().inflate(R.layout.custom_list, parent, false);
        }
        NewsItems currentItem = newsFeed.get(position);

        ImageView newsImage = (ImageView) convertView.findViewById(R.id.leftIco);
        TextView newsHeading = (TextView) convertView.findViewById(R.id.heading);
        TextView newsDesc = (TextView) convertView.findViewById(R.id.description);

        newsImage.setImageResource(R.mipmap.ic_launcher);
        newsHeading.setText(currentItem.getNewsTitle());
        newsDesc.setText(String.valueOf((currentItem.getNewsDescription())));

        return convertView;
            }
        }
    }

这是NewsItem.java

public class NewsItems {
private String newsTitle;
private String newsDescription;
private String newsUrl;
private String imageUrl;

public NewsItems(String  newsTitle, String newsDescription, String newsUrl, String imageUrl) {
    this.newsTitle = newsTitle;
    this.newsDescription = newsDescription;
    this.newsUrl = newsUrl;
    this.imageUrl = imageUrl;
}


public String getNewsTitle() {
    return newsTitle;
}

public String getNewsDescription() {
    return newsDescription;
}

public String getNewsUrl() { return newsUrl; }

public String getImageUrl() { return imageUrl; }
}

这是控制台中的错误

    W/System.err: org.json.JSONException: No value for newsItems
    W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
    W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:584)
    W/System.err:     at com.comp.app.news.fragments.NewsFragment$1.onResponse(NewsFragment.java:68)
    W/System.err:     at com.comp.app.news.fragments.NewsFragment$1.onResponse(NewsFragment.java:64)
    W/System.err:     at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
    W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
    W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    W/System.err:     at android.os.Looper.loop(Looper.java:154)
    W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6119)
    W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

谢谢。 编辑:我忘了添加NewsItem.java类,对不起

编辑:

  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("News");

    RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());

    JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
            "https://raw.githubusercontent.com/sumbganesh/temp/master/news.json",
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray NewsItems = response.getJSONArray("articles");

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

                            JSONObject temp = NewsItems.getJSONObject(i);

                            String title = temp.optString("title");
                            String description = temp.optString("description");
                            String url = temp.optString("url");
                            String urlToImage = temp.optString("urlToImage");

                            newsFeed.add(new NewsItems(title, description, url, urlToImage));
                        }
                    } catch (JSONException e){
                        Log.i("myTag", e.toString());
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Log.i("myTag", error.toString());

                }
            });

    queue.add(newsReq);

    ArrayAdapter<NewsItems> adapter = new customAdapter();

    ListView news_list =(ListView) (getActivity().findViewById(R.id.newsList));
    news_list.setAdapter(adapter);
}

这是布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@mipmap/ic_launcher"
    android:id="@+id/leftIco"
    android:maxHeight="50dp"
    android:maxWidth="50dp"/>

<TextView
    android:text="Heading"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/leftIco"
    android:layout_toEndOf="@+id/leftIco"
    android:layout_marginLeft="23dp"
    android:layout_marginStart="23dp"
    android:id="@+id/heading" />

<TextView
    android:text="Description"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/heading"
    android:layout_alignLeft="@+id/heading"
    android:layout_alignStart="@+id/heading"
    android:id="@+id/description" />

</RelativeLayout>

3 个答案:

答案 0 :(得分:0)

首先,您使用的JSON具有root作为jsonObject,然后JSONArray是articles。所以你需要使用

JSONArray NewsItems = response.getJSONObject("root").getJSONArray("articles");

而不是

JSONArray NewsItems = response.getJSONArray("newsItems");

答案 1 :(得分:0)

    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.Volley;
    import com.comp.app.news.R;
    import com.comp.app.news.activities.NewsItems;

    import org.json.JSONArray;
    import org.json.JSONException;
     import org.json.JSONObject;

    import java.util.ArrayList;
    import java.util.List;


    public class NewsFragment extends Fragment {

    private List<NewsItems> newsFeed = new ArrayList<>();

    public NewsFragment() {
    // Required empty public constructor
    }

   @Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                      Bundle savedInstanceState) {
     // Inflate the layout for this fragment
   return inflater.inflate(R.layout.fragment_news, container, false);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle    savedInstanceState) {
 super.onViewCreated(view, savedInstanceState);
 getActivity().setTitle("News");

 RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());

 JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
         "https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
         null,
         new Response.Listener<JSONObject>() {
             @Override
             public void onResponse(JSONObject response) {
                 try {
                 JSONArray NewsItems = response.getJSONArray("newsItems");

                     for (int i = 0; i < NewsItems.length(); i++) {
NewsItems item = new NewsItems();
                         JSONObject temp = NewsItems.getJSONObject(i);

                         String title = temp.getString("title");
                         String description = temp.getString("description");
                         String url = temp.getString("url");
                         String urlToImage = temp.getString("urlToImage");

                         newsFeed.add(new NewsItems(title, description, url, urlToImage));
                     }
                 } catch (JSONException e){
                     e.printStackTrace();
                 }
             }
         },
         new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {

             }
         });

     queue.add(newsReq);

 ArrayAdapter<NewsItems> adapter = new customAdapter(newsFeed,getActivity());

 ListView news_list =(ListView) (getActivity().findViewById(R.id.newsList));
 news_list.setAdapter(adapter);
}

private class customAdapter extends ArrayAdapter<NewsItems>{
Context context;
 customAdapter(ArrayList<NewsItems> newsFeed, Context context) {
     super(getActivity(), R.layout.custom_list, newsFeed);
     this.newsFeed = newsFeed;
     this.context = context;
 }

 @NonNull
 @Override
 public View getView(int position, View convertView, @NonNull ViewGroup parent) {

     if (convertView == null){
         convertView = getActivity().getLayoutInflater().inflate(R.layout.custom_list, parent, false);
     }
     NewsItems currentItem = newsFeed.get(position);

     ImageView newsImage = (ImageView) convertView.findViewById(R.id.leftIco);
     TextView newsHeading = (TextView) convertView.findViewById(R.id.heading);
     TextView newsDesc = (TextView) convertView.findViewById(R.id.description);

     newsImage.setImageResource(R.mipmap.ic_launcher);
     newsHeading.setText(currentItem.getNewsTitle());
     newsDesc.setText(String.valueOf((currentItem.getNewsDescription())));

     return convertView;
         }
     }
 }

答案 2 :(得分:0)

在这个https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson文件中,没有newsItem的值。 这就是为什么它没有得到它的价值。