2014-12-04 45 views
0

下面的代碼被用於從Web服務獲取數據,並將其存儲在我的應用程序:從Java/Android的Web服務中檢索數據。 android.os.NetworkOnMainThreadException

//GET APP INFORMATION 
public static String getAppInformation() { 

    String data = ""; 
    //test the get method data retrieval using the HttpRequest Class 

    try { 
     data = makeHttpRequest("http://www.mywebsite.com/abc.php?action=abc.get"); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return data; 
} 

如何停止讓「android.os.NetworkOnMainThreadException」異常並返回數據變量?

回答

1

打電話給你getAppInformation從線程,而不是在OnCreate()

class CallDemo extends Thread 
{ 
    public void run() 
    { 
     getAppInformation() 
    } 
} 

,並從OnCreate中()

new CallDemo().start(); 

使用的AsyncTask

class DemoClass extends AsyncTask<String, Void, String> 
{ 

    @Override 
    protected String doInBackground(String... params) { 
     // TODO Auto-generated method stub 

     String result=getAppInformation(); 

     return result; 
    } 

} 

,並在OnCreate代碼

try 
    { 
     DemoClass d=new DemoClass(); 
     d.execute(""); 
     String data=d.get(); 
    } 
    catch(Exception e) 
    { 

    } 
+0

那麼如何返回getAppInformation()中的內容呢? – cwiggo 2014-12-04 13:11:16

+1

爲此目的,你可以使用asynctask類 – 2014-12-04 13:12:01

+0

我只是沒有得到它 – cwiggo 2014-12-04 13:14:56

相關問題