如何在AsyncTask中设置doInBackground的参数?

时间:2014-01-17 06:54:44

标签: android android-asynctask

当我点击按钮时我的屏幕加载速度很慢(因为下载图像?图像文件虽然很小)但我尝试使用AsyncTask来帮助。该程序有效,但我将图像加载移动到AsyncTask以查看它是否会加载更快并且应用程序每次都崩溃。我猜它与我设置它的方式有关。我该如何解决?使用runnable线程会更好吗?谢谢!

班级:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // no title
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // set full screen
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                         WindowManager.LayoutParams.FLAG_FULLSCREEN);
    // inflate listview
    setContentView(R.layout.gmg);
    **new Load.execute(); // executes AsyncTask**
    ...
    gmgListView = (ListView) findViewById(R.id.gmg_list2);
    GMGListViewAdapter adapter = new GMGListViewAdapter(this,
                                    R.layout.gmg_list_row, rowItems);
    gmgListView.setAdapter(adapter);
    gmgListView.setOnItemClickListener(this);
}

AsyncTask:

private class Load extends AsyncTask<String, Void, Void> {

    private ProgressDialog Dialog = new ProgressDialog(GMGListViewActivity.this);

    @Override
    protected void onPreExecute() {
        Dialog.setMessage("Doing something...");
        Dialog.show();
    }
    @Override
    protected Void doInBackground(String... params) {
        SparseArray<Spanned> gmgText = null;
        Integer[] right = null;
        SparseArray<Drawable> appIcon = null;
        try {
            gmgText = ParseContent.queryGMGText();
            right = ParseContent.queryGMGRight();
            appIcon = ParseContent.queryDrawable();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // Inflate GMG's rows
        rowItems = new ArrayList<GMGRowItem>();
        for (int i = 0; i < gmgText.size(); i++) {
            GMGRowItem item = new GMGRowItem(appIcon.get(i), gmgText.get(i), right[i]);
            rowItems.add(item);
        }

        return null;
    }
    protected void onPostExecute(Void unused) {
        Dialog.dismiss();
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在代码中应用一些更改,例如......

需要在onPostExecute方法中设置列表适配器并从onCreate()中删除它。

完成后台进程后,它将与ui线程进行交互。

 protected void onPostExecute(Void unused) {
        Dialog.dismiss();
     GMGListViewAdapter adapter = new GMGListViewAdapter(this,
                                    R.layout.gmg_list_row, rowItems);
     gmgListView.setAdapter(adapter);
    }

试试这个,如果你有任何问题,请告诉我。