以下代码用于从我的Web服务获取数据并将其存储在我的应用程序中:
//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”异常并返回数据变量?
答案 0 :(得分: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 code
try
{
DemoClass d=new DemoClass();
d.execute("");
String data=d.get();
}
catch(Exception e)
{
}