У меня был проект, но, похоже, я его пропустил. Проблема заключается в парсинге автора в Json, автор не всегда присутствует. Итак, как разобрать отсутствующее поле, которое может присутствовать или нет.
Код ошибки, предоставленный моим рецензентом. Я не понимаю, что он имеет в виду и что мне нужно сделать, чтобы это исправить.
Смотрите на картинке, пожалуйста, нажмите на ссылку, чтобы увидеть картинку.
Вызвано: java.lang.IndexOutOfBoundsException: Индекс: 0, Размер: 0
введите описание изображения здесь
Это код:
// Create an empty ArrayList that we can start adding news to
List <NewsFeed> newsfeeds = new ArrayList <>();
// parse the JSON response string. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject( newsfeedJSON );
// For a given news, extract the JSONObject associated with the
// key called "response",
JSONObject response = baseJsonResponse.getJSONObject( "response" );
// Extract the JSONArray with the key called "result",
// which represents a list of results (or news).
JSONArray newsfeedArray = response.getJSONArray( "results" );
//in the newsfeedArray, I create an {@link news} object
for (int i = 0; i < newsfeedArray.length(); i++) {
// Get a single news at position i within the list of news
JSONObject currentNewsFeed = newsfeedArray.getJSONObject( i );
// Extract the value for the key called "type"
String id = currentNewsFeed.getString( "sectionId" );
// Extract the value for the key called "name"
String name = currentNewsFeed.getString( "sectionName" );
// Extract the value for the key called "title"
String title = currentNewsFeed.getString( "webTitle" );
if (title.contains( "|" )) {
String[] arrayString = title.split( "\\|" );
title = arrayString[0].trim(); //
}
// Extract the value for the key called "date"
String date = currentNewsFeed.getString( "webPublicationDate" );
// Extract the value for the key called "url"
String url = currentNewsFeed.getString( "webUrl" );
// Extract the value for the key called author tied to webtitle
JSONObject fields = currentNewsFeed.getJSONObject( "fields" );
JSONArray tags = currentNewsFeed.getJSONArray( "tags" );
JSONObject tagsObject = tags.getJSONObject( 0 );
String author;
if (fields.has( "byline" ) && (tags.length() != 0)) {
author = tagsObject.getString( "byline" );
} else author = "No Author";
//{@link news} object with the type, name, title, time,
// and url from the JSON response.
NewsFeed newsfeed = new NewsFeed( id, name, title, date, url, author);
// Add the new {@link News Feed} to the list of news feeds.
newsfeeds.add( newsfeed );
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e( "QueryUtils", "Problem parsing the news feed JSON results", e );
}
После того, как вы получили массив тегов, вы напрямую обращаетесь к данным внутри массива, как это, это вызывает исключение.
JSONArray tags = currentNewsFeed.getJSONArray( "tags" );
JSONObject tagsObject = tags.getJSONObject( 0 );
измените это на это
String author;
JSONArray tags = currentNewsFeed.getJSONArray( "tags" );
if (tags != null && tags.length() > 0 ) {
JSONObject tagsObject = tags.getJSONObject( 0 );
if (fields.has( "byline" ) && (tags.length() != 0)) {
author = tagsObject.getString( "byline" );
}
}else author = "No Author";
при этом вы получите доступ к своему массиву тегов только тогда, когда там есть хотя бы один элемент, иначе ваш автор будет «без автора».
Он обеспечивает резервное значение… даже если key не существует. Это может пригодиться в тех случаях, когда у вас нет контроля над API.
да, читал об этом, прошло много времени с тех пор, как я действительно разбирал json вручную, в основном я полагаюсь на Gson.
Привет, war_Hero! Приложение получает данные, но когда я нажимаю на него, чтобы открыть веб-страницу с новостями, приложение вылетает.
Ошибки больше нет. Но приложение больше не доступно для просмотра на телефоне.
тогда есть еще одна проблема: добавили ли вы прослушиватель кликов и установили событие клика на кнопке.
Я должен поставить url в последнюю позицию !!! вот почему приложение не было кликабельным.
Хорошо, рад, что смог помочь, пожалуйста, примите ответ, чтобы он помог другим с аналогичной проблемой.
этот код потрясающий! author = tagsObject.optString ("webtitle", "Без автора");
Еще проще был бы
tagsObject.optString("byline", "No Author");. Тогда можно забыть о блокеif..else, содержащемif (fields.has( "byline" )....