1

I was trying to retrieve images from internet and found similar samples then slightly changed the code I have found .But when I run my code I got this exception android.os.NetworkOnMainThreadException .Then I have searched for solutions and noticed that I should use Asyntask class for doing this.The problem is simple I just couldn't I get syntax errors at every line of code.Could you please help how to fix this code and make it run properly.Thanks in advance

class BackroundActivity extends AsyncTask<Void, Bitmap, Void>
{

    @Override
    protected Bitmap doInBackground(String src) throws IOException {
        HttpURLConnection con = null;

            URL url=new URL(src);
            con=(HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            InputStream input=con.getInputStream();
            Bitmap bmp=BitmapFactory.decodeStream(input);
            return bmp;

    }
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

AsyncTask is using varargs and also you didn't specify return types properly, so the correct code is the following:

class BackroundActivity extends AsyncTask<String, Void, Bitmap>
{

    @Override
    protected Bitmap doInBackground(String... src) throws IOException {
        HttpURLConnection con = null;

        URL url=new URL(src[0]);
        con=(HttpURLConnection) url.openConnection();
        InputStream input=con.getInputStream();
        Bitmap bmp = BitmapFactory.decodeStream(input);
        return bmp;

    }
}

From the docs:

The three types used by an asynchronous task are the following:

  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.
nikis
  • 11,166
  • 2
  • 35
  • 45