0

Possible Duplicate:
Not Reading text from server

i am trying to read text from a .txt file which is present on server but my code is not reading text from file i am using android version 2.1 , will you please also tell me how can i handle the exception in order to caught the error.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView tv= new TextView(this);
    StringBuilder content = new StringBuilder();


    try {
        URL url = new URL("http://linktomywebsite/textfile.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
            content.append(str +"\n");
            tv.setText(content);
        }
        in.close();
    } catch (MalformedURLException e){
    } catch (IOException e) {
        e.printStackTrace();
    }


};        
Community
  • 1
  • 1
La Chi
  • 575
  • 2
  • 7
  • 9

2 Answers2

0
 TextView tv= new TextView(this);

This creates a new TextView that is independent of your current visible layout.

You are not putting this newly created TextView in your layout anywhere so your result, which is contained within that TextView, will not be shown

Assuming your code works to retrieve the text from your site (it looks fine to me) this is likely why you aren't seeing any results.

Try calling

setContentView(tv);

after your try { } catch { } and see if that works

dymmeh
  • 22,247
  • 5
  • 53
  • 60
  • Just adding to that, if you're trying to add it to a TextView that you already have in your layout, change TextView tv= new TextView(this); to TextView tv= (TextView)findViewById(R.id.yourTextViewName); otherwise make a reference to your layout and then call yourLayout.addView(tv); – Cruceo Jun 06 '12 at 20:34
  • well after replacing TextView tv= (TextView)findViewById(R.id.yourTextViewName); , it is still not showing any text from server. – La Chi Jun 07 '12 at 09:54
0

You must link your existing TextView in the main Layout

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