doInBackground过程中的问题

时间:2012-11-18 05:53:37

标签: android android-asynctask

调用课程时遇到问题。我没有得到解决我的确切问题的方法。直到我的工作是:

Task.java:

public class Task extends AsyncTask<Void, Void, String>
{
    Context context;
    FragmentActivity currentActivity;
    ProgressDialog dialog;
    public Task(FragmentActivity activity)
    {
        currentActivity = activity;
        context=Constant.getContext();
    }
    @Override
    protected void onPreExecute()
    {
        dialog=ProgressDialog.show(currentActivity, "Please wait...", "Loading..."); 

}

@Override
protected String doInBackground(Void... params)
{
    ActivityWeatherSetting hh = new ActivityWeatherSetting();
    hh.initialize();
    return "success";
}

@Override
protected void onPostExecute(String params)
{
    //asyncclass.dismissProgressDialog();
    dialog.dismiss();
}
}

AsyncClass.java:

public abstract class AsyncClass extends Activity
{
    protected static final String TAG = AsyncClass.class.getSimpleName();


public ProgressDialog progressDialog;

private boolean destroyed = false;

Context context;

@Override
protected void onDestroy()
{
    super.onDestroy();
    destroyed = true;
}

public void showLoadingProgressDialog()
{
    context=Constant.getContext();
    this.showProgressDialog("Loading. Please wait...");
    Log.d("this",this.toString());
}


public void showProgressDialog(CharSequence message)
{
    if (progressDialog == null)
    {
        progressDialog = new ProgressDialog(this);
        progressDialog.setIndeterminate(true);
    }

    progressDialog.setMessage(message);
    progressDialog.show();
}

public void dismissProgressDialog()
{
    if (progressDialog != null && !destroyed)
    {
        progressDialog.dismiss();
    }
}
}

ActivityWeatherSetting.java:

public void initialize()
    {
        LayoutInflater layout = new LayoutInflater(Constant.getContext()) {


        @Override
        public LayoutInflater cloneInContext(Context newContext) {
            return null;
        }
    };
    view=(View)layout.inflate(R.layout.activity_grid_layout, null);
    boolean bResult = initializeData();

    if (bResult != false ){
        bResult = initializeView();
    }

    if (bResult == false){
        Log.e(TAG,"Init data failed");
        return;
    }
        drawWeatherScreen();
}    

private void updateDataOfCurrentLocation(){
    requestUpdateWeather();
}
private void requestUpdateWeather(){
    Message msgFetchData = new Message();
    msgFetchData.what = REG_GET_WEATHER_START;
    m_HandleRequest.sendMessage(msgFetchData);      
}



private void initializeHandleRequest(){
    m_Runnable = new Runnable(){

        //@Override
        public void run() {
            requestUpdateWeather();
        }           
    };
    /* Setting up handler for ProgressBar */
    m_HandleRequest = new Handler(){
        @Override
        public void handleMessage(Message message) {
            int nRequest = message.what;

            switch(nRequest){
            case REG_GET_WEATHER_START:
                String strWOEID = m_Preferneces.getLocation();
                if (strWOEID == null){
                    Log.e(TAG,"Can not get WOEID");
                    //m_ProgressDialog.dismiss();
                    //displayNotifyCation(R.string.strFetchFailed);
                    return;
                } else {
                     //Get weather information 
                    m_WeatherInfo = m_DataModel.getWeatherData(strWOEID);           
                }

                Message msgRegSearch = new Message();
                msgRegSearch.what = REG_GET_WEATHER_FINISH;
                sendMessage(msgRegSearch);
                break;

            case REG_GET_WEATHER_FINISH:
                if (m_WeatherInfo != null){
                    updateWeatherInfo(m_WeatherInfo);
                    //notifyUpdateTime();
                }                   
                //m_ProgressDialog.dismiss();
                m_HandleRequest.postDelayed(m_Runnable, (ONE_MINUTE*m_Preferneces.getTimeUpdate()));
                break;

                 default:
                     Log.e(TAG,"Can not handle this message");
                     break;
            }
        }
    };      
}    



private boolean initializeView(){
    m_TextLocation = (TextView)view.findViewById(R.id.weatherset_location_txtview);
    m_Temperature = (TextView)view.findViewById(R.id.weatherset_temp_txtview);
    m_Humimidy = (TextView)view.findViewById(R.id.weatherset_humidity_txtview);
    m_Visibility = (TextView)view.findViewById(R.id.weatherset_visibility_txtview);
    m_WeatherIcon = (ImageView) view.findViewById(R.id.weather_icon);
    m_Date = (TextView)view.findViewById(R.id.dateTime);

    if ((m_TextLocation == null) || (m_Temperature == null) || 
            (m_Humimidy == null) || (m_WeatherIcon == null) ||
            (m_Visibility == null) || (m_Date == null)){
        Log.e(TAG,"View init failed");
        return false;
    }

    return true;
}

private boolean initializeData(){
    /* Get application context */
    Context appContext = view.getContext();

    /* Get preference instance */
    m_Preferneces = WeatherPreferences.getInstance(appContext);
    if (m_Preferneces == null){
        Log.e(TAG, "Get preference instance failed, check please");
        return false;
    }

    /* Get instance of data model */
    m_DataModel = WeatherDataModel.getInstance();
    if (m_DataModel == null){
        Log.e(TAG,"Can not get data model");
        return false;
    }

    initializeHandleRequest();

    return true;
}    
private void drawWeatherScreen(){
    /
    updateDataOfCurrentLocation();
}
private void updateWeatherInfo(WeatherInfo weatherInfo)
{
    try
    {
    if (weatherInfo == null){
        Log.e(TAG,"Weather is null");
        return;
    }

    String strCode = weatherInfo.getCode();
    int nCode = getImageByCode(strCode);
    m_WeatherIcon.setImageResource(nCode);

    boolean bIsC = m_Preferneces.getTempFmt();

    String strFmt;
    String strTemp = weatherInfo.getTemperature(WeatherInfo.TEMPERATURE_FMT_CELSIUS);
    if (bIsC == true){
        strFmt = view.getContext().getString(R.string.str_temperature_fmt); 
    } else {
        strFmt = view.getContext().getString(R.string.str_temperature_fmt_f);
        strTemp = WeatherDataModel.convertC2F(strTemp);
    }

    //String strTemperature = String.format(strFmt, strTemp);
    strTemperature = String.format(strFmt, strTemp);

    m_TextLocation.setText(weatherInfo.getCity());
    m_Temperature.setText(strTemperature);
    m_Date.setText(weatherInfo.getDate());

    TextView humidity=(TextView)view.findViewById(R.id.humidityValue);
    TextView visibility=(TextView)view.findViewById(R.id.visiValue);
    strFmt = view.getContext().getString(R.string.str_humidity_fmt);
    String strHumidity = String.format(strFmt, weatherInfo.getHumidity());
    //m_Humimidy.setText(strHumidity);
    humidity.setText(strHumidity);
    strFmt = view.getContext().getString(R.string.str_visi_fmt);
    String strVisi = String.format(strFmt, weatherInfo.getVisibility());
    //m_Visibility.setText(strVisi);
    visibility.setText(strVisi);
    }
    catch(Exception e)
    {
        //Toast.makeText(ActivityWeatherSetting.this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
private int getImageByCode(String strCode){
    int nImageCode = R.drawable.a0;

    if (strCode == null){
        Log.e(TAG,"Code is null");
        return nImageCode;
    }

    int nCode = Integer.parseInt(strCode);

    int nNumber= YahooWeatherHelper.m_ImageArr.length;
    for (int i=0; i < nNumber; i++){
        if (nCode == YahooWeatherHelper.m_ImageArr[i][1]){
            return YahooWeatherHelper.m_ImageArr[i][0];
        }
    }
    return nImageCode;
}

LogCat中的例外:

11-18 13:38:20.510: E/AndroidRuntime(585): FATAL EXCEPTION: AsyncTask #1
11-18 13:38:20.510: E/AndroidRuntime(585): java.lang.RuntimeException: An error occured while executing doInBackground()
11-18 13:38:20.510: E/AndroidRuntime(585):  at android.os.AsyncTask$3.done(AsyncTask.java:278)
11-18 13:38:20.510: E/AndroidRuntime(585):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-18 13:38:20.510: E/AndroidRuntime(585):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-18 13:38:20.510: E/AndroidRuntime(585):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-18 13:38:20.510: E/AndroidRuntime(585):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-18 13:38:20.510: E/AndroidRuntime(585):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
11-18 13:38:20.510: E/AndroidRuntime(585):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-18 13:38:20.510: E/AndroidRuntime(585):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-18 13:38:20.510: E/AndroidRuntime(585):  at java.lang.Thread.run(Thread.java:856)
11-18 13:38:20.510: E/AndroidRuntime(585): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-18 13:38:20.510: E/AndroidRuntime(585):  at android.os.Handler.<init>(Handler.java:121)
11-18 13:38:20.510: E/AndroidRuntime(585):  at com.net.elderlyhealth.weather.ActivityWeatherSetting$3.<init>(ActivityWeatherSetting.java:384)
11-18 13:38:20.510: E/AndroidRuntime(585):  at com.net.elderlyhealth.weather.ActivityWeatherSetting.initializeHandleRequest(ActivityWeatherSetting.java:384)
11-18 13:38:20.510: E/AndroidRuntime(585):  at com.net.elderlyhealth.weather.ActivityWeatherSetting.initializeData(ActivityWeatherSetting.java:561)
11-18 13:38:20.510: E/AndroidRuntime(585):  at com.net.elderlyhealth.weather.ActivityWeatherSetting.initialize(ActivityWeatherSetting.java:137)
11-18 13:38:20.510: E/AndroidRuntime(585):  at com.net.elderlyhealth.weather.Task.doInBackground(Task.java:44)
11-18 13:38:20.510: E/AndroidRuntime(585):  at com.net.elderlyhealth.weather.Task.doInBackground(Task.java:1)
11-18 13:38:20.510: E/AndroidRuntime(585):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
11-18 13:38:20.510: E/AndroidRuntime(585):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-18 13:38:20.510: E/AndroidRuntime(585):  ... 5 more
11-18 13:38:23.420: I/dalvikvm(585): threadid=3: reacting to signal 3
11-18 13:38:23.561: I/dalvikvm(585): Wrote stack traces to '/data/anr/traces.txt'
11-18 13:38:23.920: I/dalvikvm(585): threadid=3: reacting to signal 3
11-18 13:38:24.032: I/dalvikvm(585): Wrote stack traces to '/data/anr/traces.txt'
11-18 13:38:24.940: E/WindowManager(585): Activity com.net.elderlyhealth.view.ViewPagerFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4149f628 that was originally added here
11-18 13:38:24.940: E/WindowManager(585): android.view.WindowLeaked: Activity com.net.elderlyhealth.view.ViewPagerFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4149f628 that was originally added here
11-18 13:38:24.940: E/WindowManager(585):   at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
11-18 13:38:24.940: E/WindowManager(585):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
11-18 13:38:24.940: E/WindowManager(585):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
11-18 13:38:24.940: E/WindowManager(585):   at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
11-18 13:38:24.940: E/WindowManager(585):   at android.view.Window$LocalWindowManager.addView(Window.java:537)
11-18 13:38:24.940: E/WindowManager(585):   at android.app.Dialog.show(Dialog.java:278)
11-18 13:38:24.940: E/WindowManager(585):   at android.app.ProgressDialog.show(ProgressDialog.java:116)
11-18 13:38:24.940: E/WindowManager(585):   at android.app.ProgressDialog.show(ProgressDialog.java:99)
11-18 13:38:24.940: E/WindowManager(585):   at android.app.ProgressDialog.show(ProgressDialog.java:94)
11-18 13:38:24.940: E/WindowManager(585):   at com.net.elderlyhealth.view.SampleGridTwoFragment$1.onItemClick(SampleGridTwoFragment.java:119)
11-18 13:38:24.940: E/WindowManager(585):   at android.widget.AdapterView.performItemClick(AdapterView.java:292)
11-18 13:38:24.940: E/WindowManager(585):   at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
11-18 13:38:24.940: E/WindowManager(585):   at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
11-18 13:38:24.940: E/WindowManager(585):   at android.widget.AbsListView$1.run(AbsListView.java:3168)
11-18 13:38:24.940: E/WindowManager(585):   at android.os.Handler.handleCallback(Handler.java:605)
11-18 13:38:24.940: E/WindowManager(585):   at android.os.Handler.dispatchMessage(Handler.java:92)
11-18 13:38:24.940: E/WindowManager(585):   at android.os.Looper.loop(Looper.java:137)
11-18 13:38:24.940: E/WindowManager(585):   at android.app.ActivityThread.main(ActivityThread.java:4424)
11-18 13:38:24.940: E/WindowManager(585):   at java.lang.reflect.Method.invokeNative(Native Method)
11-18 13:38:24.940: E/WindowManager(585):   at java.lang.reflect.Method.invoke(Method.java:511)
11-18 13:38:24.940: E/WindowManager(585):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-18 13:38:24.940: E/WindowManager(585):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-18 13:38:24.940: E/WindowManager(585):   at dalvik.system.NativeStart.main(Native Method)

我在SO中看到了AsyncTask问题中的很多问题,但这些都没有帮助我。我需要帮助...

1 个答案:

答案 0 :(得分:0)

问题在于,当您致电hh.initialize()时,您已经在后台线程中,创建Handler为时已晚。实际上,您的代码正在尝试从后台线程中执行大量UI工作。您应该将UI线程外部实际需要完成的内容分离到一个单独的方法中,并且只从AsyncTask的doInBackground调用该方法。