0

I am having trouble with the exception NetworkOnMainThreadException.

So I have to take a function to an asynctask, the problem is that I have to send two parameters which not is as sending and as I receive them.

These are the parameters that would need to send, so the asynctask receive them

TypedArray array
Boolean true

public void SetImages(TypedArray array){
   SetImages(array, true); // OLD CALL
   new task().execute   // NEW CALL
} 

This is the code that I need to bring to the asynctask

public void SetImages(TypedArray array, boolean reflected){

    final int reflectionGap = 4;

//          Drawable[] drawables = new Drawable[array.length()];
//          mImages = new CarouselImageView[array.length()];
    mImages = new CarouselImageView[MainActivity.aL_home.size()];
    Log.e("TAG", "SIZE OF: "+MainActivity.aL_home.size());
    for(int i = 0; i< MainActivity.aL_home.size(); i++)
    {
        try {
            Log.e("TAG","url: "+MainActivity.aL_home.get(i).getUrl_imagen());
//              drawables[i] = array.getDrawable(i);
//              Bitmap originalImage = ((BitmapDrawable)drawables[i]).getBitmap();
            Bitmap originalImage = BitmapFactory.decodeStream((InputStream)new URL(MainActivity.aL_home.get(i).getUrl_imagen()).getContent());
            if(reflected){
                int width = originalImage.getWidth();
                int height = originalImage.getHeight();

                // This will not scale but will flip on the Y axis
                Matrix matrix = new Matrix();
                matrix.preScale(1, -1);

                // Create a Bitmap with the flip matrix applied to it.
                // We only want the bottom half of the image
                Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
                        height / 2, width, height / 2, matrix, false);

                // Create a new bitmap with same width but taller to fit
                // reflection
                Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
                        (height + height / 2), Config.ARGB_8888);

                // Create a new Canvas with the bitmap that's big enough for
                // the image plus gap plus reflection
                Canvas canvas = new Canvas(bitmapWithReflection);
                // Draw in the original image
                canvas.drawBitmap(originalImage, 0, 0, null);
                // Draw in the gap
                Paint deafaultPaint = new Paint();
                canvas.drawRect(0, height, width, height + reflectionGap,
                        deafaultPaint);
                // Draw in the reflection
                canvas.drawBitmap(reflectionImage, 0, height + reflectionGap,
                        null);

                // Create a shader that is a linear gradient that covers the
                // reflection
                Paint paint = new Paint();
                LinearGradient shader = new LinearGradient(0,
                        originalImage.getHeight(), 0,
                        bitmapWithReflection.getHeight() + reflectionGap,
                        0x70ffffff, 0x00ffffff, TileMode.CLAMP);
                // Set the paint to use this shader (linear gradient)
                paint.setShader(shader);
                // Set the Transfer mode to be porter duff and destination in
                paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
                // Draw a rectangle using the paint with our linear gradient
                canvas.drawRect(0, height, width,
                        bitmapWithReflection.getHeight() + reflectionGap, paint);

                originalImage = bitmapWithReflection;
            }

            CarouselImageView imageView = new CarouselImageView(mContext);
            imageView.setImageBitmap(originalImage);
            imageView.setIndex(i);

            ////////imageView.setLayoutParams(new CarouselOld.LayoutParams(120, 180));
            ////////imageView.setScaleType(ScaleType.MATRIX);
            mImages[i] = imageView;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
jlopez
  • 6,287
  • 2
  • 51
  • 90

4 Answers4

1

NetworkOnMainThreadException

This kind of Exception is thrown if you are trying to manipulate and changing your UI from background thread that is not synchronized with Main(UI) thread.

AsyncTask provides a few methods where you can update your UI:

  • onPreExecute
  • onProgressUpdate
  • onPostExecute

And you should perform any UI updates only in mentioned methods.

This is the code that I need to bring to the asynctask

So move your method into AsyncTask class and pass required parameters(TypedArray and Boolean) via constructor of AsyncTask i.e

Task task = new Task(arr, boolVariable);
task.execute();
Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
Simon Dorociak
  • 33,095
  • 10
  • 66
  • 104
0

I think, you still call the networking code on the main thread. Most likely, forgot to comment out something.

See How to fix android.os.NetworkOnMainThreadException?

Community
  • 1
  • 1
18446744073709551615
  • 15,352
  • 3
  • 89
  • 124
0

so the question is how to pass parameters to the AsyncTask?

The format is

private class MyTask extends AsyncTask<Params, Progress, Result> { ... }

http://developer.android.com/reference/android/os/AsyncTask.html

So you can define your AsyncTask like

private class SetImagesTask extends AsyncTask<TypedArray, Void, Void> { 
    protected Void doInBackground(TypedArray... typedArrays) {
        TypedArray array = typedArrays[0];
        ...
    }
    ...
}

and call it like

new SetImagesTask.execute(array);

For a boolean, you could use the main class field, or a static variable, so you could set it before the execute(array). Alternatively, you can wrap the boolean into the second TypedArray, and pass the array of them like execute(new TypedArray[] {array, booleanArray});

Mcingwe
  • 2,062
  • 2
  • 18
  • 16
0

NetworkOnMainThread Exception occurs because you are running a network related operation on the main UI Thread.This is only thrown for applications targeting the Honeycomb SDK or higher

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

You should be using asynctask.

http://developer.android.com/reference/android/os/AsyncTask.html

In onCreate()

new TheTask().execute();

You can also pass parameters like url to the constructor of AsyncTask and use the same in doInBackground()

class TheTask extends AsyncTask<Void,Void,Void>
{
 protected void onPreExecute()
{           super.onPreExecute();
        //display progressdialog.
} 

protected void doInBackground(Void ...params)//return result here
{  
    //http request. do not update ui here

    return null;
} 

protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{     
        super.onPostExecute(result);
        //dismiss progressdialog.
        //update ui using the result returned form doInbackground()
 } 
 }

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Raghunandan
  • 131,557
  • 25
  • 223
  • 252