我有一个ListView。当我单击listview行的按钮时,将在main.xml中创建一个按钮,我在自定义listview适配器中拥有该按钮的onclicklistener。我将在sqlite中保存该按钮的单击,并通过该sqlite更新gridview适配器。
所以我的问题是,当我单击按钮时,GridView不会自我更新,当我关闭应用程序并再次打开它时,它会被更新。
我试着用notifydatasetchanged()但没用。
这是自定义列表视图适配器中的代码

holder.checkbox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             String text = holder.tvName.getText().toString();
             String image = holder.tvimageurl.getText().toString();
             DatabaseHandler db = new DatabaseHandler(activity);
             db.addContact(new Contact(text, image));
             db.close();

在主要活动中
    GridView listView = (GridView) findViewById(R.id.gridview1);
    imgAdapter = new ImageAdapter(this);
    listView.setAdapter(imgAdapter);
    imgAdapter.notifyDataSetChanged();

图像适配器代码。
public class ImageAdapter extends BaseAdapter {

    Activity activity;
    List<Contact> item;
    LayoutInflater inflater;
    ImageAdapter imgAdapter;
    private DisplayImageOptions options;
    private DisplayImageOptions options2;
    ImageLoader imageLoader;
    private Contact objBean;
    String getUrl,getId;
    ObjectOutputStream oos;
    FileOutputStream fos;



    public ImageAdapter(Activity act) {
        this.activity=act;

        inflater = act.getLayoutInflater();


        DatabaseHandler db = new DatabaseHandler(activity);
        item = db.getAllContacts();
        db.close();
}

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

    @Override
    public Contact getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final LinearLayout imageView;
        if (convertView == null) {
            imageView = (LinearLayout)        inflater.inflate(R.layout.item_grid_image, parent, false);
        } else {
            imageView = (LinearLayout) convertView;
        }

最佳答案

在调用notifydatasetchanged之前,需要先将数据添加到imageadapter。或者重新创建它并再次设置为gridview
UPD:
好,然后将加载代码放在imageadapter中的单独方法中,并在添加新数据后调用refresh

public ImageAdapter(Activity act) {
        this.activity=act;

        inflater = act.getLayoutInflater();
        refresh();
}

void refresh()
{
        DatabaseHandler db = new DatabaseHandler(activity);
        item = db.getAllContacts();
        db.close();
        notifyDatasetChanged();
}

但最好在单击按钮时手动将新联系人添加到imageadapter
public void onClick(View v) {
    String text = holder.tvName.getText().toString();
    String image = holder.tvimageurl.getText().toString();
    DatabaseHandler db = new DatabaseHandler(activity);
    Contact contact = new Contact(text, image)
    db.addContact(contact);
    db.close();
    imgAdapter.addItem(contact)
    imgAdapter.notifyDatasetChanged();
}

10-08 14:50