0

I am trying to read all the text from server, I think that my code is not retrieving text from server will you please help me how can I fix this problem, I am new to android development. Thanks in advance

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

                }


};        


}
La Chi
  • 575
  • 2
  • 7
  • 9
  • 1
    Try the code given in this post http://stackoverflow.com/questions/2094529/android-read-contents-of-a-url-content-missing-after-in-result – Nirali Jun 07 '12 at 11:45

2 Answers2

0

Take these lines

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

out of while loop

Use StringBuilder object (declared before loop) in while loop and append the strings in that. After while loop take string from StringBuilder and do tv.setText(string)

Saurabh
  • 7,894
  • 2
  • 23
  • 31
  • i have edited my code , but it is still not working , how can i check is it reading text from server ? – La Chi Jun 07 '12 at 11:57
0

May be you can try like this, just a thought only :

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);
UVM
  • 9,776
  • 6
  • 41
  • 66