-2

我对所有这些 android 编程都是新手。在编写了一些代码之后,我得到了以下名为 ipString 的字符串。我想在文本视图中显示字符串。

这是我现在所拥有的。

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

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);
4

3 回答 3

0

使用setText()它将显示您的响应文本。

TextView myTextView = (TextView) findViewById(R.id.textview1);
myTextView.setText(ipString);
于 2013-08-31T03:49:11.987 回答
0

以这种方式使用 setText():

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

无论如何,您应该将这两行放在您的尝试中,这样它只会在 HTTP 请求成功时打印字符串。

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。

于 2013-08-31T04:04:27.887 回答
0

像这样使用 setText() 方法:

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

text.setText(yourstringvalue);
于 2013-08-31T06:52:49.250 回答