2012-11-20 54 views
0

我是新的android开发人员。HttpUrlConnection android

我想从我的网络服务器访问数据的代码....

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    URL url; 
    try { 
     url = new URL("http://www.mysite.net/LEDstate.txt"); 

     HttpURLConnection urlConnection = (HttpURLConnection) url 
       .openConnection(); 

     InputStream in = urlConnection.getInputStream(); 

     InputStreamReader isw = new InputStreamReader(in); 

     int data = isw.read(); 
     while (data != -1) { 
      char current = (char) data; 
      data = isw.read(); 
      //System.out.print(current); 


      TextView t = (TextView) findViewById(R.id.ledstate); 

      t.setText(current); 
     } 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

}

但数据不会出现在Screen.There是在TextView中没有变化。

我已检查权限,他们没事。

任何帮助? 谢谢。

+1

是否有任何错误之外?如果是这样,发布logcat输出。并尝试调试。 char current有什么价值? (检查它不为空) –

+0

没有错误....但没有显示我的数据...显示默认的Hello World! – antkan

回答

6

我想你会得到NetworkOnMainThreadException,但是因为你正在捕捉所有的异常,所以错误被抑制了。

您无法在Ui线程上发出网络请求。将网络操作移至Asynctask。

2

TextView while循环

StringBuilder sb = new StringBuilder(); 
while (data != -1) { 
     char current = (char) data; 
     data = isw.read(); 
     sb.append(current); 
} 

TextView t = (TextView) findViewById(R.id.ledstate); 
t.setText(sb.toString()); 
+0

与此一起,请检查它的情况@nandeesh在另一个答案中提到 – sujith

+0

我这样做,但没有...同样的问题...显示默认的Hello世界!没有我的数据.... – antkan

+0

您是否将您的代码移动到单独的'Thread'?如果在此之后它不起作用请删除try:catch:块并提供异常日志。 – sujith