ERJAN
ERJAN

Reputation: 24500

How do I avoid network on main thread exception if I already use AsyncTask?

It seems to me I m not really calling URL,network operations right from MainActivity.

but the exception still occurs:

public class MainActivity extends ActionBarActivity {

    private final String LOG_TAG = MainActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {            
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ProcessData test = new ProcessData();
        test.doInBackground("mysql") ;
    }

//separate file ProcessData.java
public class ProcessData extends AsyncTask<String, Void, String> {

public String createValidUrl(String s){
       .....//code in this method works fine
}
public String doInBackground(String ...params){
        String validUrl = createValidURL(params[0]);                   
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        URL url = new URL(validUrl);
        urlConnection = (HttpURLConnection) url.openConnection();        
        urlConnection.setRequestMethod("GET");            
        urlConnection.connect();           

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
            while((line = reader.readLine()) != null) {

                buffer.append(line + "\n");
            }
            urlConnection.disconnect();
            reader.close();

            return buffer.toString();
}
}

The network main thread exception still occurs, i read other SO posts. I can wrap my http connection code into new thread, but I want to find exactly what is wrong

Upvotes: 2

Views: 1157

Answers (2)

Ajit Pratap Singh
Ajit Pratap Singh

Reputation: 1289

You have to call

test.execute();

instead of

test.doInBackground("mysql") ;

Upvotes: 3

Bossie
Bossie

Reputation: 3612

You have to call the execute method on an AsyncTask in order to run it in a background thread. What you're doing is calling doInBackground directly from the main thread.

Upvotes: 5

Related Questions