-4

I am trying to pull news form json. But i am working in fragment instead of activity.

I have no error in code but when i run the app, i get error "org.json.JSONException: No value for newsItem" in the console and in logcat.

This is my 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;
            }
        }
    }

This is 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; }
}

And this is error in console

    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)

Thank you. Edit: I forgot to add NewsItem.java class, Sorry

Edit:

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

This is Layout file

<?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>
Ganesh
  • 19
  • 2
  • 9

3 Answers3

0

First of all you are using JSON that has root as jsonObject and then JSONArray is articles. So you need to use

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

instead of

JSONArray NewsItems = response.getJSONArray("newsItems");
Pradeep Kumar Kushwaha
  • 2,231
  • 3
  • 23
  • 34
  • Actually, i am just using that json file for test purpose. My orignal json file dose not have root. (check here https://raw.githubusercontent.com/sumbganesh/temp/master/news.json) – Ganesh Feb 25 '17 at 10:01
  • I got W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7903a49ff4c0, error=EGL_BAD_MATCH when i used JSONArray NewsItems = response.getJSONObject("root").getJSONArray("articles"); – Ganesh Feb 25 '17 at 10:03
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;
         }
     }
 }
Nitesh Mishra
  • 574
  • 1
  • 6
  • 14
  • I got E/EGL_emulation: tid 26503: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH) W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7903a49a38c0, error=EGL_BAD_MATCH – Ganesh Feb 25 '17 at 10:09
  • error is coming because your variable NewsItem and Model NewsItem matches. instead of – Nitesh Mishra Feb 25 '17 at 10:30
  • Did the same and got this --> E/EGL_emulation: tid 24228: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH) W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7903b58901c0, error=EGL_BAD_MATCH – Ganesh Feb 25 '17 at 10:52
  • this error is related to emulator try running your app in device and check this link for better understanding http://stackoverflow.com/a/41948265/7604342 – Nitesh Mishra Feb 25 '17 at 11:19
  • Thank you Nitesh. It worked. But still i am not able to see any news or data on my page. Is there anything else i need to change? – Ganesh Feb 25 '17 at 11:27
  • yeah i think you are not binding data to adapter thats why list is not showing can i see your entire code like NewsItems. – Nitesh Mishra Feb 25 '17 at 11:51
  • I have added both newsFragment.java and NewsItem.java above in the question. I have also add the layout in Edit. – Ganesh Feb 25 '17 at 11:58
  • I have made the changes and i have got the error saying I/Choreographer: Skipped 41 frames! The application may be doing too much work on its main thread. – Ganesh Feb 27 '17 at 04:47
  • there is no error listed in console, but still i nothing appears on the screen. – Ganesh Feb 27 '17 at 07:15
  • My Url contains an api key, i think that is causing problem, because when i use the sample file on my github, it works fine but when i use the newapi, it don't show any thing, the url is like this https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=061dcabcdabcdabcdabcdb01f3c – Ganesh Feb 27 '17 at 11:50
0

In this https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson file, there is no value of newsItem. that's why it didn't get value of it.