如何在textview中打印字符串?

时间:2013-08-31 03:29:56

标签: java android json textview

我是所有这个Android编程的新手。在计算出几个代码后,我得到以下名为ipString的字符串。我想在textview中显示字符串。

这就是我现在所拥有的。

我应该添加什么才能使其正常工作?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("Rami","Rami");
    DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://jsonip.com");
    // Depends on your web service
    httppost.setHeader("Content-type", "application/json");

    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);           
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");

        }
        result = sb.toString();
        JSONObject jObject = new JSONObject(result);
        String ipString = jObject.getString("ip");
        Log.d("ip", ipString);
    } catch (Exception e) { 
        // Oops
    }
    finally {
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
    }

    TextView myTextView = (TextView) findViewById(R.id.textview1);

3 个答案:

答案 0 :(得分:0)

使用setText()它会显示您的回复文字。

TextView myTextView = (TextView) findViewById(R.id.textview1);
myTextView.setText(ipString);

答案 1 :(得分:0)

以这种方式使用setText():

TextView myTextView = (TextView) findViewById(R.id.textview1);
myTextView.setText(ipString);

无论如何你应该把这两行放在你的try中,这样只有在HTTP Request成功的情况下它才能打印出来。

try {
        HttpResponse response = httpclient.execute(httppost);           
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");

        }
        result = sb.toString();
        JSONObject jObject = new JSONObject(result);
        String ipString = jObject.getString("ip");
        Log.d("ip", ipString);

        TextView myTextView = (TextView) findViewById(R.id.textview1);
        myTextView.setText(ipString);

    } catch (Exception e) { 
        // Oops
    }
    finally {
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
    }

顺便说一下,您应该真正阅读(并尝试理解)文档并学习如何使用IDE。

答案 2 :(得分:0)

使用这样的setText()方法:

String yourstringvalue;
TextView text = (TextView) findViewById(R.id.textviewID);

text.setText(yourstringvalue);