简体   繁体   中英

parsing json results java

I'm getting an error when trying to parse the json for a theguardian newsfeed and it is saying there is no value for the results. I'm a noobie, and i'm not sure which part of my code is the problem. Whenever I run the app, it runs correctly but doesn't show any news in the feed

Here is my code

public class NewsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {

    private static final String LOG_TAG = NewsActivity.class.getName();

    private static final String GUARDIAN_REQUEST_URL =
            "http://content.guardianapis.com/search?section=games&order-by=newest&api-key=test";

    private static final int NEWS_LOADER_ID = 1;

    private NewsAdapter mAdapter;

    private TextView mEmptyStateTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_activity);

        ListView newsListView = (ListView) findViewById(R.id.list);

        mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
        newsListView.setEmptyView(mEmptyStateTextView);

        mAdapter = new NewsAdapter(this, new ArrayList<News>());

        newsListView.setAdapter(mAdapter);

        newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                News currentNews = mAdapter.getItem(position);

                Uri newsUri = Uri.parse(currentNews.getUrl());

                Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);

                startActivity(websiteIntent);
            }
        });

        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            LoaderManager loaderManager = getLoaderManager();

            loaderManager.initLoader(NEWS_LOADER_ID, null, this);
        } else {
            View loadingIndicator = findViewById(R.id.loading_indicator);
            loadingIndicator.setVisibility(View.GONE);

            mEmptyStateTextView.setText(R.string.no_internet_connection);
        }
    }

    @Override
    public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
        return new NewsLoader(this, GUARDIAN_REQUEST_URL);
    }

    @Override
    public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
        View loadingIndicator = findViewById(R.id.loading_indicator);
        loadingIndicator.setVisibility(View.GONE);

        mEmptyStateTextView.setText(R.string.no_news);

        if (news != null && !news.isEmpty()) {
            mAdapter.addAll(news);
            updateUi(news);
        }
    }

    private void updateUi(List<News> news) {
    }

    @Override
    public void onLoaderReset(Loader<List<News>> loader) {
        mAdapter.clear();
    }
}

QueryUtils

public class QueryUtils {

private static final String LOG_TAG = QueryUtils.class.getSimpleName();

private QueryUtils() {
}

public static List<News> fetchNewsData(String requestUrl) {
    // Create URL object
    URL url = createUrl(requestUrl);

    // Perform HTTP request to the URL and receive a JSON response back
    String jsonResponse = null;
    try {
        jsonResponse = makeHttpRequest(url);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem making the HTTP request.", e);
    }

    List<News> newss = extractResultFromJson(jsonResponse);

    return newss;
}

private static URL createUrl(String stringUrl) {
    URL url = null;
    try {
        url = new URL(stringUrl);
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Problem building the URL ", e);
    }
    return url;
}

private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the news JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return jsonResponse;
}

private static String readFromStream(InputStream inputStream) throws IOException {
    StringBuilder output = new StringBuilder();
    if (inputStream != null) {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String line = reader.readLine();
        while (line != null) {
            output.append(line);
            line = reader.readLine();
        }
    }
    return output.toString();
}

private static List<News> extractResultFromJson(String newsJSON) {
    if (TextUtils.isEmpty(newsJSON)) {
        return null;
    }

    List<News> newss = new ArrayList<>();
    try {

        JSONObject baseJsonResponse = new JSONObject(newsJSON);

        JSONArray newsArray = baseJsonResponse.getJSONArray("results");

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

            JSONObject currentNews = newsArray.getJSONObject(i);

            String title =  currentNews.getString("webTitle");

            long date = currentNews.getLong("webPublicationDate");

            String url = currentNews.getString("webUrl");

            News news = new News(title, date, url);

            newss.add(news);
        }

    } catch (JSONException e) {
        Log.e("QueryUtils", "Problem parsing the news JSON results", e);
    }

    return newss;
}

}

Adapter

public class NewsAdapter extends ArrayAdapter<News> {

public NewsAdapter(Context context, List<News> news) {
    super(context, 0, news);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.news_list_item, parent, false);
    }

    News currentNews = getItem(position);

    TextView titleView = (TextView) listItemView.findViewById(R.id.title);
    String title = currentNews.getTitle();
    titleView.setText(title);

    TextView dateView = (TextView) listItemView.findViewById(R.id.date);
    String dateToString = String.valueOf(currentNews.getDate());
    String date = dateToString.substring(0, 10);
    dateView.setText(date);

    return listItemView;
}

} Manifest

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".NewsActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Error message

E/QueryUtils: Problem parsing the news JSON results
          org.json.JSONException: No value for results
              at org.json.JSONObject.get(JSONObject.java:392)
              at org.json.JSONObject.getJSONArray(JSONObject.java:587)
              at com.example.android.newsapp.QueryUtils.extractResultFromJson(QueryUtils.java:117)
              at com.example.android.newsapp.QueryUtils.fetchNewsData(QueryUtils.java:40)
              at com.example.android.newsapp.NewsLoader.loadInBackground(NewsLoader.java:30)
              at com.example.android.newsapp.NewsLoader.loadInBackground(NewsLoader.java:8)
              at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:315)
              at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
              at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:64)
              at android.os.AsyncTask$2.call(AsyncTask.java:333)
              at java.util.concurrent.FutureTask.run(FutureTask.java:266)
              at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
              at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
              at java.lang.Thread.run(Thread.java:764)

Any help or criticism is appreciated

First you need to get the “response” object, only then look for “result” array there

JSONObject baseJsonResponse = new JSONObject(newsJSON).getJSONObject(“response”);

JSONArray newsArray = baseJsonResponse.getJSONArray("results");

Look more careful at your json 😉

Replace your extractResultFromJson method with following code

private static List<News> extractResultFromJson(String newsJSON) {
    if (TextUtils.isEmpty(newsJSON)) {
        return null;
    }

    List<News> newss = new ArrayList<>();
    try {

        JSONObject baseJsonResponse = new JSONObject(newsJSON);
        JSONObject mainResponse = baseJsonResponse.getJSONObject("response");

        JSONArray newsArray = mainResponse.getJSONArray("results");

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

            JSONObject currentNews = newsArray.getJSONObject(i);

            String title = currentNews.getString("webTitle");

            long date = currentNews.getLong("webPublicationDate");

            String url = currentNews.getString("webUrl");

            News news = new News(title, date, url);

            newss.add(news);
        }

    } catch (JSONException e) {
        Log.e("QueryUtils", "Problem parsing the news JSON results", e);
    }

    return newss;
}

Also after you get the result of the feed, call notifyDataSetChange() on the adapter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM