0

The following code is used to fetch data from my web service and store it on my app:

//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;
}

How do I STOP getting the "android.os.NetworkOnMainThreadException" exception and also return the data variable?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
cwiggo
  • 2,541
  • 9
  • 44
  • 87

1 Answers1

1

call your getAppInformation from thread, not from oncreate()

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

and from oncreate()

 new CallDemo().start();

By using asynctask

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

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

        String result=getAppInformation();

        return result;
    }

}

and oncreate code

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

    }
Ravi
  • 34,851
  • 21
  • 122
  • 183