2013-04-09 2 views
0

예외 NetworkOnMainThreadException에 문제가 있습니다.특정 매개 변수를 전송하기위한 Asynctask 구성

그래서 asynctask에 함수를 가져와야하는데, 문제는 송수신이 아닌 두 개의 매개 변수를 보내야한다는 것입니다.

보낼 필요가 매개 변수이다, 그래서 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(); 
     } 
    } 

} 

답변

1

NetworkOnMainThreadException

당신이 조작을 시도하고 홈페이지 (UI) 스레드와 동기화되지 않습니다 백그라운드 스레드에서 UI를 변경하는 경우 예외 이런 종류의 슬로우됩니다

.

  • onPreExecute
  • onProgressUpdate
  • onPostExecute

그리고 당신은 단지 한 방법에 어떤 UI 업데이트를 수행해야합니다

AsyncTask를 사용하면 UI를 업데이트 할 수있는 몇 가지 방법을 제공합니다.

내가 그래서 AsyncTask를 즉의 생성자를 통해 필요한 매개 변수 (하는 TypedArray 및 부울) AsyncTask를 클래스로 방법을 이동하고 전달하는 AsyncTask를

에 가져 오는 데 필요한 코드입니다

Task task = new Task(arr, boolVariable); 
task.execute(); 
0

나는 여전히 당신을 생각 AsyncTask를 가져다하는 데 필요한 코드가

TypedArray array 
Boolean true 

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

을받을 주 스레드에서 네트워킹 코드를 호출하십시오. 대체로 뭔가를 주석으로 쓰는 걸 잊었습니다.

는 참조 How to fix android.os.NetworkOnMainThreadException?

0

그래서 AsyncTask에 매개 변수를 전달하는 방법은 무엇입니까?

형식은

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

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

그래서 당신이

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

처럼 AsyncTask를 정의하고 부울 들어

new SetImagesTask.execute(array); 

처럼 호출 할 수 있습니다, 당신은 c를 ould는 main 클래스 필드 또는 정적 변수를 사용하므로 execute (배열) 전에 설정할 수 있습니다.또는 부울을 두 번째 TypedArray로 래핑하고 execute (new TypedArray [], array, booleanArray)와 같은 배열을 전달할 수 있습니다. 당신은 단지 벌집 SDK를 대상으로 응용 프로그램에 발생합니다 또는

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

높은 당신은 AsyncTask를를 사용한다 메인 UI Thread.This에 네트워크 관련 작업을 실행하기 때문에

0

NetworkOnMainThread 예외가 발생합니다.

또한) (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() 
} 
} 

때를 같은 AsyncTask를 생성자에 URL과 같은 매개 변수를 전달하고 사용할 수 있습니다

new TheTask().execute(); 

에서 onCreate()에서

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

비동기 작업이 실행되면 작업은 4 단계로 진행됩니다.

  1. onPreExecute(), 작업이 실행되기 전에 UI 스레드에서 호출됩니다. 이 단계는 일반적으로 사용자 인터페이스에 진행률 표시 줄을 표시하여 작업을 설정하는 데 사용됩니다.

  2. doInBackground (Params ...), onPreExecute() 실행 직후 백그라운드 스레드에서 호출됩니다. 이 단계는 오랜 시간이 걸릴 수있는 백그라운드 계산을 수행하는 데 사용됩니다. 비동기 작업의 매개 변수가이 단계로 전달됩니다. 계산 결과는이 단계에서 리턴되어야하며 마지막 단계로 다시 전달됩니다. 이 단계에서는 publishProgress (Progress ...)를 사용하여 하나 이상의 진행 단위를 게시 할 수 있습니다. 이 값은 UI 스레드의 onProgressUpdate (Progress ...) 단계에 게시됩니다.

  3. onProgressUpdate (Progress ...), publishProgress (진행 ...) 호출 후 UI 스레드에서 호출됩니다. 실행의 타이밍은 정의되지 않습니다. 이 메소드는 백그라운드 계산이 아직 실행 중일 때 사용자 인터페이스에 진행 상태를 표시하는 데 사용됩니다. 예를 들어 진행률 표시 줄에 애니메이션을 적용하거나 텍스트 필드에 로그를 표시하는 데 사용할 수 있습니다.

  4. onPostExecute (결과), 백그라운드 계산이 끝난 후 UI 스레드에서 호출됩니다. 백그라운드 계산의 결과는이 단계에 매개 변수로 전달됩니다.

관련 문제