2012-10-31 68 views
0

下面是我的异步类异步返回null即使使用AsyncTask.Status.FINISHED

public class GetBitMapFromURL extends AsyncTask<String, Integer, String> 
{ 
    byte[] tempByte; 
    private Bitmap bmap; 
@Override 
    protected String doInBackground(String... params) 
    { 
     // TODO Auto-generated method stub 
     String stringUrl = params[0]; 
     //bmap = null; 
     try 
     { 
      URL url = new URL(stringUrl); 
      InputStream is = (InputStream) url.getContent(); 
      byte[] buffer = new byte[8192]; 
      int bytesRead; 
      ByteArrayOutputStream output = new ByteArrayOutputStream(); 
      while ((bytesRead = is.read(buffer)) != -1) 
      { 
       output.write(buffer, 0, bytesRead); 
      } 
      tempByte = output.toByteArray(); 
     } 
     catch (MalformedURLException e) 
     { 
      e.printStackTrace(); 

     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 

     } 
     return "Success"; 
    } 

    @Override 
    protected void onPostExecute(String result) 
    { 
     super.onPostExecute(result); 
     Bitmap tempBitMap = BitmapFactory.decodeByteArray(tempByte, 0, tempByte.length); 
     //Log.d("Bitmap bmap value on PostExecute", "bmap="+bmap); 
     setBitMap(tempBitMap); 
     //imageView.setImageBitmap(bImg); 
    } 
    void setBitMap(Bitmap bitMapSet) 
    { 
     this.bmap = bitMapSet; 
     //Log.d("Bitmap bmap value", "bmap="+bmap); 
    } 
    Bitmap returnBitmap() 
    { 
     //Log.d("Bitmap bmap value", "bmap="+bmap); 
     return bmap; 
    } 

} 

尽管做以下我的活动中,returnBitMap()返回null。

GetBitMapFromURL gbmap1 = new GetBitMapFromURL();  //Obtain medium bitmap 
    gbmap1.execute(applicationImageMediumURL); 
    if(gbmap1.getStatus() == AsyncTask.Status.FINISHED) 
    { 
     applicationMediumBitMap = gbmap1.returnBitmap(); 
    } 

向我建议我哪里出错了。

+0

你调试过吗? *状态是否已完成? –

+0

@JonSkeet是这样做的 –

+0

你有这样的循环或什么? if语句只会被执行一次......如果你使用调试器,你应该知道null被分配到的行。 – Joel

回答

1

不要做,使用AsyncTask.onPostExecute()方法来更新像

@Override 
protected void onPostExecute(String result) 
{ 
    super.onPostExecute(result); 
    applicationMediumBitMap = BitmapFactory.decodeByteArray(tempByte, 0, tempByte.length); 
    //Log.d("Bitmap bmap value on PostExecute", "bmap="+bmap); 

    // call any method on the activity to continue the process.. 
    otherStuff(); 
} 

的UI和删除代码

if(gbmap1.getStatus() == AsyncTask.Status.FINISHED) 
    { 
     applicationMediumBitMap = gbmap1.returnBitmap(); 
    } 

    // other stuff code 

在活动的onCreate()(我猜)。将下面的代码放在它自己的Activity方法中,并在onPostExecute()中调用它。

private void otherStuff() { 
    // other stuff code 
} 
相关问题