解析java的数组中的android api json数组

时间:2018-05-07 00:32:23

标签: java android arrays json parsing

我正在为我的课程制作一个简单的新闻应用程序,并且我使用The Guardian的API来填充我的Feed。我已经完成了文章Title,Date和URL的所有工作,但是在添加Section和Author名称后,我似乎无法填充Feed。该设备说没有找到新闻,日志说"错误响应代码:429"

非常感谢任何帮助/批评!

活动

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&show-tags=contributor";

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

适配器

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

    TextView authorView = (TextView) listItemView.findViewById(R.id.firstname);
    String authorFirstName = currentNews.getAuthorFirstName();
    authorView.setText(authorFirstName);

    TextView lastNameView = (TextView) listItemView.findViewById(R.id.lastname);
    String authorLastName = currentNews.getAuthorLastName();
    lastNameView.setText(authorLastName);

    TextView sectionView = (TextView) listItemView.findViewById(R.id.section);
    String section = currentNews.getSection();
    sectionView.setText(section);

    return listItemView;
}

}

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

            String date = currentNews.getString("webPublicationDate");

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

            String section = currentNews.getString("sectionName");

            JSONArray tagsArray = currentNews.getJSONArray("tags");

            for (int j = 0; j < tagsArray.length(); j++) {

                JSONObject currentTag = tagsArray.getJSONObject(j);

                String authorFirstName = currentTag.getString("firstName");
                String authorLastName = currentTag.getString("lastName");

                News news = new News(title, date, url, authorFirstName, authorLastName, section);
                newss.add(news);
            }
        }

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

    return newss;
}

}

0 个答案:

没有答案