0

我正在尝试将我的上下文从一个类传递到另一个扩展类AsyncTask。所以这里的代码:

loadSomeStuff slb = new SamsungLB().new loadSomeStuff();
                        slb.execute(USA.this.getSherlockActivity());

异步任务:

public void execute(SherlockFragmentActivity sherlockActivity) {
            // TODO Auto-generated method stub
            this.ctx = sherlockActivity;
        }

然后活动没有成功。所以我去检查上下文是否为空:

if (ctx == null) {
                System.out.print("null");
            }

是的,我是对的,我的上下文是空的!我觉得我从来没有调用过执行方法:/有什么建议吗?这是我的完整 AsyncTask 类:

public class loadSomeStuff extends AsyncTask<String, Integer, String> {

ProgressDialog dialog;
Context ctx;

protected void onPreExecute() {
    dialog = new ProgressDialog(ctx);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(false);
    dialog.setIndeterminate(false);
    dialog.setMessage(getResources().getString(R.string.searching));
    dialog.show();
}

@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    //fillinglistview//
    }
    if (ctx == null) {
        System.out.print("null");
    }
    return null;
}

protected void onProgressUpdate(Integer... progress) {

}

protected void onPostExecute(String result) {
    listview.setAdapter(new MyListAdapterSamsung(getActivity(),
            beanClass));
    if (beanClass.isEmpty()) {
        Toast.makeText(getSherlockActivity(), "No Connection",
                Toast.LENGTH_LONG).show();
    }

}

public void execute(SherlockFragmentActivity sherlockActivity) {
    // TODO Auto-generated method stub
    this.ctx = sherlockActivity;
}
}
4

1 回答 1

0

您可以像这样首先创建一个构造函数:

public loadSomeStuff(SherlockFragmentActivity sherlockActivity) {

    // TODO Auto-generated method stub
    this.ctx = sherlockActivity;
}

并且不要忘记检查是否已添加片段

protected void onPostExecute(String result) {
   if(isAdded()){
        listview.setAdapter(new MyListAdapterSamsung(getActivity(),
               beanClass));
        if (beanClass.isEmpty()) {
            Toast.makeText(getSherlockActivity(), "No Connection",
                   Toast.LENGTH_LONG).show();
       }
   }
}

然后当你创建它时:

LoadSomeStuff slb = new SamsungLB().new loadSomeStuff(USA.this.getSherlockActivity());

然后像正常的异步任务一样执行!

 slb.execute();

希望我的回答能帮到你:)

于 2013-08-03T20:43:54.783 回答