我应该使用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/