java - Android - 如何在 TextView 中打印结果?

标签 java android textview

我应该使用setText(),但是我应该如何使用它而不是System.out.println()? 我想在 TextView 中打印结果。该代码是一个 json 阅读器。抱歉,我需要写一些文字来发布我的问题。

public class JsonReader extends Activity{

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

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}

public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
    System.out.println(json.toString());
    System.out.println(json.get("display"));
    //TextView tv = (TextView) findViewById( R.id.tv );
    //tv.setText(json.toString());
    //tv.setText(json.get("display"));

}

}

最佳答案

如果您想在手机上而不是按照 johnrao07 的建议在 LogCat 控制台上查看结果,则需要在 TextView 中打印结果。

要在 TextView 中打印结果,首先在 Activity_main.xml 布局文件中添加 TextView 小部件。

<TextView
        android:id="@+id/text_view_id"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

然后 JsonReader.java 类主函数而不是 System.out.println(json.toString()); 调用 ((TextView) findViewById(R.id.text_view_id))。 setText(json.toString());

关于java - Android - 如何在 TextView 中打印结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34379584/

相关文章:

android - Rx Android 并行组合对同一服务的多个调用

Android - TextView 中的文本不左对齐/垂直对齐

Android 单击 ListViewItem 时加载 fragment

android - android中不同字体的不同TTF文件

java - JSON 查询不更新 TextView

java - 魔方旋转算法

java - 如何解析textarea并使用jsoup进行选择

java - 类数组中的 NullPointer

java - 通过 Java 发送 HTML 到任何电子邮件地址

Android:ListView 项目中的平铺位图