0

我有一个名为LoadXMLData的 AsyncTask 类,如您所见,我在doInBackground()方法中解析 XML 数据。

public class LoadXMLData extends AsyncTask<String, RSSFeed, RSSFeed>{

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;


private Context context;
RSSFeed feed;



public LoadXMLData(Context context) {
    this.context = context;
    mProgressDialog = new ProgressDialog(context);
    mProgressDialog.setMessage("Molimo Vas, sačekajte. Podaci se učitavaju.");
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    mProgressDialog.show();
    Log.d("OVDE SAM:", "onPreExecute()");
}

@Override
protected RSSFeed doInBackground(String... urls) {
    // Obtain feed
    DOMParser myParser = new DOMParser();
    feed = myParser.parseXml(urls[0]);
    Log.d("OVDE SAM:", "PARSIRAM XML");
    return feed;
}



@Override
protected void onPostExecute(RSSFeed result) {
    mProgressDialog.dismiss();

    super.onPostExecute(result);
}

}

而且我有几个片段,我需要从该 AsyncTask 获取数据。我怎么能那样做?

这是一个名为NajnovijeFragment的片段的代码。

public class NajnovijeFragment extends Fragment{

GridView lv;
RSSFeed feed;
CustomListAdapter adapter;
private String RSSFEEDURL = "http://balkanandroid.com/feed/";

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_najnovije, container,
            false);     


    lv = (GridView) view.findViewById(R.id.GridView1);

    // Set an Adapter to the ListView
    adapter = new CustomListAdapter();
    lv.setAdapter(adapter);

    // Set on item click listener to the ListView
    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // actions to be performed when a list item clicked
            int pos = arg2;

            Bundle bundle = new Bundle();
            bundle.putSerializable("feed", feed);
            Intent intent = new Intent(getActivity(), DetailsActivity.class);
            intent.putExtras(bundle);
            intent.putExtra("pos", pos);
            startActivity(intent);

        }
    });

    return view;
}

@Override
public void onDestroy() {
    super.onDestroy();
    adapter.imageLoader.clearCache();
    adapter.notifyDataSetChanged();
}

class CustomListAdapter extends BaseAdapter {

    private LayoutInflater layoutInflater;
    public ImageLoader imageLoader;

    public CustomListAdapter() {

        layoutInflater = (LayoutInflater) getActivity().getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        imageLoader = new ImageLoader(getActivity().getApplicationContext());
    }

    public int getCount() {
        // TODO Auto-generated method stub
        // Set the total list item count
        return feed.getItemCount();
    }

    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // Inflate the item layout and set the views
        View listItem = convertView;
        int pos = position;
        if (listItem == null) {
            listItem = layoutInflater.inflate(R.layout.list_item, null);
        }

        // Initialize the views in the layout
        ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);
        TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
        TextView tvDate = (TextView) listItem.findViewById(R.id.tvDate);

        // Set the views in the layout
        imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv);
        tvTitle.setText(feed.getItem(pos).getTitle());
        tvDate.setText(feed.getItem(pos).getDate());

        return listItem;
    }

}

}

4

3 回答 3

4

从 ASyncTask 获取数据的最简单方法是实现回调。

创建接口:

public interface OnXMLLoadFinishedListener {
  public void onXMLDataReady(RSSFeed results);
}

在您的 LoadXMLData 中:

private OnXMLLoadFinishedListener listener;

public void setOnXMLLoadFinishedListener(OnXMLLoadFinishedListener listener){
  this.listener = listener;
}

@Override
protected void onPostExecute(RSSFeed result) {
    super.onPostExecute(result);
    listener.onXMLDataReady(RSSFeed results);
}

在你的片段中:

public class NajnovijeFragment extends Fragment implements OnXMLLoadFinishedListener{

并覆盖 onXMLDataReady:

@override
public void onXMLDataReady(RSSFeed results){
   //display your data.
}

确保在创建 AsyncTask 实例时设置侦听器,否则这将不起作用:

LoadXMLData xmlLoader = new LoadXMLData();
xmlLoader.setOnXMLLoadFinishedListener(this);
于 2013-07-11T01:35:55.940 回答
1

您的 AsyncTask 已经知道上下文,因此您可以在 onPostExecute 中回调您的活动(出于说明目的称为 ActivityMain)。例如

@Override
protected void onPostExecute(String result) {
 super.onPostExecute(result);
 ((ActivityMain) context).loadCompleteHandler(param1,param2,...)
}

然后由您决定如何在活动中实现 loadCompleteHandler。现在您的活动可能不存在,因此当活动被删除时,您必须小心取消 AsyncTask。属于一个活动的片段也可以访问该活动。

于 2013-07-10T15:21:25.897 回答
1

AsyncTask 是一个与 UI 非常相关的 Class,如果你需要用这个 XML 解析更新 UI,你应该考虑这个:

  • 使异步任务成为片段中的内部类或
  • 将片段传递给您的异步任务
  • 在 onPostExecute() 中更新片段的视图

无论如何,您应该检查您的活动是否为空,如果是...避免更新视图,例如:

onPostExecute(Object xml) {
   if(getActivity != null) {
      // update Views like...
      textViewLabel.setText(parsedXml.getTitle);
   }
}

我建议你使用 SafeAsyncTask,它是 Roboguice 项目中的一个 java 类,只有一个文件,它与 java.util.concurrent.Callable 相关,只需复制并粘贴源即可:

SafeAsyncTask.java

如何使用它!

于 2013-07-10T15:09:23.750 回答