how to refresh my gridView?

南楼画角 提交于 2019-12-06 09:37:44

You need to add data to ImageAdapter first before calling notifyDataSetChanged. Or recreate it and set again to your GridView

UPD: Ok, then put loading code to separate method inside your ImageAdapter and call refresh after you add new data

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

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

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

But better add new contact manually to your ImageAdapter when you click on your button

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();
}

You can force the Adapter to update itself within your onClick method e.g.

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();
    notifyDataSetChanged(); // This will do the trick
 }

EDIT

As you are getting the data when you restart that means it is definitely being saved in the database OK, this suggests that when you invalidate the Adapter it isn't reloading the database. Try something like a custom method in ImageAdapter like this:

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();
    reloadData();  // will refresh the data
    notifyDataSetChanged(); // will update the contents
 }

private void reloadData() {
    DatabaseHandler db = new DatabaseHandler(activity);
    item = db.getAllContacts();
    db.close();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!