Android自定义适配器添加来自asynctask的数据将不会被添加

时间:2015-12-09 13:39:09

标签: android android-asynctask android-arrayadapter

我目前尝试将从异步任务收到的​​数据添加到自定义适配器。在第一次调用任务时,有一个空的“通知”列表。在第二次和第三次呼叫时,收到的通知必须添加到现有的通知列表中。

我的问题是新通知不会添加到现有列表中。新通知将替换旧列表。

private class LoadNotificationsTask extends AsyncTask<String, Integer, ArrayList<Notification>> {
    NotificationFragment fragment;
    String parameters;

    private LoadNotificationsTask(NotificationFragment fragment, String parameters) {
        this.fragment = fragment;
        this.parameters = parameters;
    }

    @Override
    protected ArrayList<Notification> doInBackground(String... params) {
        try {
            return Client.getNotifications(this.parameters);
        } catch (Exception e) {
            return new ArrayList<Notification>();
        }
    }

    @Override
    protected void onPostExecute(ArrayList<Notification> notifications) {
        NotificationListAdapter notificationListAdapter = new NotificationListAdapter(notifications);
        setListAdapter(notificationListAdapter);
    }
}


public class NotificationListAdapter extends BaseAdapter {
    private ArrayList<Notification> notifications;

    public NotificationListAdapter(ArrayList<Notification> notifications) {
        super();
        this.notifications = notifications;

    }


    @Override
    public int getCount() {
        return this.notifications.size();
    }

    @Override
    public Object getItem(int position) {
        return this.notifications.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.notificationlist_item, parent, false);
        }
        final Notification notification = (Notification) this.getItem(position);

        TextView headline = (TextView) convertView.findViewById(R.id.notilist_hostname);
        headline.setText(notification.getNAME1() + "\\" +notification.getNAME2());


        return convertView;

    }

2 个答案:

答案 0 :(得分:0)

首先在AsyncTask外启动ListView适配器即。在onCreate()

ICovariantKeyValuePair<string, Animal>

然后使用以下代码编辑您的AsyncTask postExecute()

 // Declare class variable
 ArrayList<Notification> mNotifications;
 NotificationListAdapter notificationListAdapter;

 // inside onCreate()
 mNotifications = new ArrayList<Notification>();
 notificationListAdapter = new NotificationListAdapter(mNotifications);
 setListAdapter(notificationListAdapter);

答案 1 :(得分:0)

可能更改getItemId函数的返回值。

@Override
public long getItemId(int position) {
    return 0;//change return position;
}