У меня проблема с заполнением отдельного TextView
содержимого того же JSON.
Каждый фрагмент имеет ListView
, заполненный адаптером. Данные извлекаются из файла JSON
. Сначала я импортирую данные из JSONArray
и добавляю их к объекту Article
, созданному отдельно:
JSONObject e = articlesJsonResponse.getJSONObject(i);
String title = e.getString("title");
int itemId = e.getInt("id");
Article article = new Article(title, itemId);
articles.add(article);
Затем я создал ArticleAdapter
, куда я помещаю этот контент в ListView
. Это работает.
В моем Activity
я создаю список из этого:
ListView mainListView = (ListView) findViewById(R.id.main_list);
mAdapter = new ArticleAdapter (getActivity(), new ArrayList<Article>());
mainListView.setAdapter(mAdapter);
Теперь я бы хотел создать TextView в том же упражнении, который бы вытягивал «заголовок» из первого объекта Article в списке.
TextView featuredImageTitle = (TextView) findViewById(R.id.featuredimage_title);
featuredImageTitle.setText(??????????);
Должен ли я передать эту информацию из адаптера? Или из Article
объекта? Или я должен прочитать его с позиции 0 в списке, который я построил для ListView
?
Вот мой полный код, который импортирует содержимое и создает объект.
открытый финальный класс QueryUtils {
public QueryUtils() {
}
// Returns new URL object from the URL String
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building URL", e);
}
return url;
}
// makes a HTTP request to the URL and returns String
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 articles JSON.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
}
}
return jsonResponse;
}
// Query the JSON info and return a list of {@link Article} objects.
public static List<Article> extractArticles(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<Article> articles = extractFromJson(jsonResponse);
// Return the list of articles
return articles;
}
/**
* Convert the {@link InputStream} into a String which contains the
* whole JSON response from the server.
*/
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();
}
/**
* Return a list of {@link Article} objects that has been built up from
* parsing a JSON response.
*/
public static List<Article> extractFromJson(String articleJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(articleJSON)) {
return null;
}
// Create an empty ArrayList that we can start adding earthquakes to
List<Article> articles = new ArrayList<>();
// Try to parse JSON response. 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 JSONArray from the JSON response string
JSONArray articlesJsonResponse = new JSONArray(articleJSON);
// For each article in the articleArray, create an Article object
for (int i=0; i < articlesJsonResponse.length(); i++) {
// Parse the response given by the json string and
// build up a list of article objects with the corresponding data.
JSONObject e = articlesJsonResponse.getJSONObject(i);
String title = e.getString("title");
int articleId = e.getInt("id");
int views = e.getInt("views");
int comments = e.getInt("comments");
String thumb = e.getString("image");
String url = e.getString("url");
String date = e.getString("date");
Article article = new Article(title, articleId, views, comments, thumb, url, date);
articles.add(article);
}
} 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 JSON results", e);
}
// Return the list of articles
return articles;
}
}