0

我正在尝试从服务器读取所有文本,我认为我的代码没有从服务器检索文本,请你帮我解决这个问题,我是 android 开发的新手。提前致谢

public class TestActivity extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView tv= (TextView)findViewById(R.id.my_text);


                try {

                    URL url = new URL("http://www.google.com:80/");
                    StringBuilder content = new StringBuilder();
                    // read text returned by server

                    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                    String line;
                    while ((line = in.readLine()) != null) {
                        content.append(line +"\n");
                    }
                    tv.setText(content.toString());
                    setContentView(tv);

                    in.close();
                }

                catch (MalformedURLException e) {

                    System.out.println("Malformed URL: " + e.getMessage());

                }

                catch (IOException e) {

                    System.out.println("I/O Error: " + e.getMessage());

                }


};        


}
4

2 回答 2

0

走这些线

tv.setText(line);
setContentView(tv);

退出while循环

在 while 循环中使用 StringBuilder 对象(在循环之前声明)并在其中附加字符串。在 while 循环之后,从 StringBuilder 获取字符串并执行 tv.setText(string)

于 2012-06-07T11:44:04.400 回答
0

也许你可以这样尝试,只是一个想法:

StringBuilder content = new StringBuilder();
                // read text returned by server
                BufferedReader in = new BufferedReader(new InputStreamReader(new URL("http://www.google.com:80/").openConnection().getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    content.append(line +"\n");
                }

tv.setText(content.toString());
setContentView(tv);
于 2012-06-07T11:54:18.653 回答