2013-12-21 44 views
2

我正在一个android项目>>>> 当我尝试在android的doInBackground()方法中做任何代码...它不会给出错误,但不会运行正确.... 这是我的代码...我们可以把我们的编程doInBackground()在android

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> 
{ 
    protected Bitmap doInBackground(String... urls) 
    { 
     button.setVisibility(View.VISIBLE); 
     return DownloadImage(urls[0]); 
    } 
    protected void onPostExecute(Bitmap result) 
    { 

     ImageView img = (ImageView) findViewById(R.id.img); 
     img.setImageBitmap(result); 
    } 
} 

此代码正常工作,当我删除button.setVisibility(View.VISIBLE);

我的查询,我们可以做这样可见性关闭或节目的类型doInBackground()方法....

+2

你不能更新'UI'在'doInBackground' –

+1

此线button.setVisibility(View.VISIBLE);在onPostExecute(位图结果)它可能会帮助你 – mayuri

+1

@Shayanpourvatan如果我们可以更新,而不是为什么它不运行... PLZ看到我的完整代码http://pastie.org/8567194 –

回答

4

您必须在UI线程中设置可见性,否则它将无法工作。如果您在不同的线程中使用MessageHandler或可以使用runOnUiThread(使用可运行)来设置可见性。例如:

runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       // set visibility here 
      } 
}); 
+1

。这些真的有用答案..... Thanku。 –

1

你可以把此行button.setVisibility(View.VISIBLE);onPreExcute() mehod异步任务的

你可以不更新您的用户界面doInBackground()How to use AsyncTask in android

1

由于此方法在单独的(非UI)线程中执行,因此无法更新doInBackground()中的任何UI元素。

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> 
{ 

    protected void onPreExecute(){ 
     button.setVisibility(View.VISIBLE); 
    } 

    protected Bitmap doInBackground(String... urls) 
    { 
     return DownloadImage(urls[0]); 
    } 
    protected void onPostExecute(Bitmap result) 
    { 
     ImageView img = (ImageView) findViewById(R.id.img); 
     img.setImageBitmap(result); 
    } 
} 
+2

.. thanku..good答案....但我们可以在非gui方法中运行gui theread ...... + 1 –

2
在doInBackground

()方法,你不能做UI Realated操作使用onPreExecute()

如果您需要做的UI相关的操作使用onPreExcuteMethod()或onPostExcute()即

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> 
{ 

protected void onPreExcute(){ 
// Before starting the function. 
button.setVisibility(View.VISIBLE); 
} 
protected Bitmap doInBackground(String... urls) 
{ 

    return DownloadImage(urls[0]); 
} 
protected void onPostExecute(Bitmap result) 
{ 
// after completion of the function. 
//  button.setVisibility(View.VISIBLE); 

    ImageView img = (ImageView) findViewById(R.id.img); 
    img.setImageBitmap(result); 
} 

}

我认为这会工作,或者你可以使用基于后EXCUTE方法你功能

+1

..thanku..good回答....但我们可以在非gui方法中运行gui theread ...... + 1 –

+0

是的,但是我们必须使用runonUIThread()方法来做到这一点,我不会在大多数情况下更喜欢这种方法。 –

1

要在doInBackground中使用UI,那么您需要使用runOnUiThread。

runOnUiThread(new Runnable() { 
        public void run() { 
         // some code #3 (Write your code here to run in UI thread) 

        } 
       }); 

感谢

+1

。这些真的有帮助答案..... Thanku。 +1 –

相关问题