Search code examples
androidandroid-asynctasknetworkonmainthread

How to fix NetworkOnMainThreadException in Android by using AsyncTask


When I wrote this code It gives NetworkOnMainThreadException so I want to implement it using AsyncTask Although I have seen many questions and answers about this Error but not able to Write it . I want to pass an argument to Asynctask class and want to assign returned data to a variable in the current class .Colud you please help me. Here is My code

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    int tem = 1940+position;
    String temp = ""+tem;
    String ReceivedData ="<";
    GettingInternetData something = new GettingInternetData(temp);
    try {
        ReceivedData = something.getMoviesData();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

GettingInternetData.java

public class GettingInternetData {

    String y = null;
    public GettingInternetData(String year) {
        // TODO Auto-generated constructor stub
        y = year;
    }
public String getMoviesData() throws Exception
{
    BufferedReader toRead = null;
    String data = null;
    try
    {
        HttpClient client = new DefaultHttpClient();
        URI url = new URI("URL goes here which requires an argument temp");
        HttpGet getting = new HttpGet();
        getting.setURI(url);
        HttpResponse resp = client.execute(getting);
        toRead = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        StringBuffer alldata = new StringBuffer();
        String l ="";
        String nl = System.getProperty("line.Separator");
        while((l = toRead.readLine()) !=null)
        {
            alldata.append(l + nl);
        }
        toRead.close();
        data = alldata.toString();
        return data;
    }
    finally{
        if (toRead != null){
            try{
                toRead.close();
                return data;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
}
}

Thanks in Advance


Solution

  • You'll want to pass arguments to your custom AsyncTask, have it do the work in the doInBackground() method and return any results. You can then process the results in the onPostExecute() method. For a more detailed explanation of AsyncTask you may find this article helpful: http://po.st/Cei3m2