从JSON提取的对象中将字符串获取到TextView

时间:2019-01-14 19:52:37

标签: android android-studio textview

我在用相同JSON的内容填充单独的TextView时遇到问题。

每个片段都有一个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中提取“ title”。

TextView featuredImageTitle = (TextView) findViewById(R.id.featuredimage_title);
featuredImageTitle.setText(??????????);

我应该从适配器传递此信息吗?还是来自Article对象?还是应该从为ListView构建的列表中的0位置读取它?

这是我的完整代码,用于导入内容并创建对象。

公共最终类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;
}

}

1 个答案:

答案 0 :(得分:0)

如果您只需要访问列表中的第一个对象标题

获取列表的0个位置,但还要检查列表大小是否大于0,以免出现索引异常

喜欢

  if(articles.size > 0){

    featuredImageTitle.setText(articles.get(0).getTitle)
 }

但是如果您需要从列表中单击的对象获取标题,则需要对ListView实现OnItemClickListener

mainListView.setOnItemClickListener(new OnItemClickListener()
{
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
    { 
        featuredImageTitle.setText(articles.get(position).getTitle);
    }

并确保在列表内的第一个父级布局上设置android:descendantFocusability="blocksDescendants"