0

While inserting my listview gets refreshed automatically but not update when the item in the listview is updated. It only updates on database. I can see the listview is updated when I close the application and open again, or come back from previous activity.

I found some discussion related to my problem. Like: Refresh ListView with ArrayAdapter after editing an Item . Her I found that make a new method to populate the Listview and call it in the onResume method of your activity. And the problem has been solved using this. But I do not get how to make new method mentioned like there. Could anybody help me to make it understandable?

My code in activity class:

personNamesListView = (ListView) findViewById(R.id.traineeslist);
    traineeListAdapter = new ArrayAdapter<Trainee>(this,
            android.R.layout.simple_list_item_1,
            currentTraining.getTraineeArrayList());

    personNamesListView.setAdapter(traineeListAdapter);

protected void onResume() {
    super.onResume();
}

And this way I populated my personNamesListView using method stringToString() in model class;

public void loadTraineeList() {

    DatabaseHelper db = DatabaseHelper.getInstance();

    this.traineeArrayList = new ArrayList <Trainee>();

    Cursor cursor = db.select("SELECT * FROM person p JOIN attendance a ON p._id = a.person_id WHERE training_id="+Integer.toString(this.getId())+";");

    while (cursor.moveToNext()) {
        Trainee trainee = new Trainee();
        trainee.setID(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.PERSON_ID)));
        trainee.setFirstname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_FIRSTNAME)));
        trainee.setLastname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_LASTNAME)));
        trainee.setJobTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_JOBTITLE)));
        trainee.setEmail(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_EMAIL)));
        trainee.setCompany(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_COMPANY)));
        trainee.setDepartment(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_DEPARTMENT)));
        trainee.setBadgeNumber(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_BADGE)));


        // Pass to the arraylist
        this.traineeArrayList.add(trainee);
    }
}
public ArrayList<Trainee> getTraineeArrayList() {
    return traineeArrayList;
}

public void setTraineeArrayList(ArrayList<Trainee> traineeArrayList) {
    this.traineeArrayList = traineeArrayList;
}

I insert and Update data into database into one method:

public void storeToDB() {

    DatabaseHelper db = DatabaseHelper.getInstance();

    db.getWritableDatabase();

    if (this.id == -1) {
        // Person not yet stored into Db => SQL INSERT
        // ContentValues class is used to store a set of values that the
        // ContentResolver can process.
        ContentValues contentValues = new ContentValues();

        // Get values from the Person class and passing them to the
        // ContentValues class
        contentValues.put(DatabaseHelper.PERSON_FIRSTNAME, this
                .getFirstname().trim().toUpperCase());
        contentValues.put(DatabaseHelper.PERSON_LASTNAME, this
                .getLastname().trim().toUpperCase());
        contentValues.put(DatabaseHelper.PERSON_JOBTITLE, this
                .getJobTitle().trim().toUpperCase());
        contentValues.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
        contentValues.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
                .trim().toUpperCase());
        contentValues.put(DatabaseHelper.PERSON_DEPARTMENT, this
                .getDepartment().trim().toUpperCase());
        contentValues.put(DatabaseHelper.PERSON_BADGE, this
                .getBadgeNumber().trim().toUpperCase());

        // here we insert the data we have put in values
        this.setID((int) db.insert(DatabaseHelper.TABLE_PERSON,
                contentValues));

    } else {
        // Person already existing into Db => SQL UPDATE

        ContentValues updateTrainee = new ContentValues();
        updateTrainee.put(DatabaseHelper.PERSON_FIRSTNAME, this
                .getFirstname().trim().toUpperCase());
        updateTrainee.put(DatabaseHelper.PERSON_LASTNAME, this
                .getLastname().trim().toUpperCase());
        updateTrainee.put(DatabaseHelper.PERSON_JOBTITLE, this
                .getJobTitle().trim().toUpperCase());
        updateTrainee.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
        updateTrainee.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
                .trim().toUpperCase());
        updateTrainee.put(DatabaseHelper.PERSON_DEPARTMENT, this
                .getDepartment().trim().toUpperCase());
        updateTrainee.put(DatabaseHelper.PERSON_BADGE, this
                .getBadgeNumber().trim().toUpperCase());

        db.update(DatabaseHelper.TABLE_PERSON, updateTrainee,
                DatabaseHelper.PERSON_ID+"= ?", new String[]{Integer.toString(this.getId())});

        System.out.println("Data updated");

    }

}
Community
  • 1
  • 1
bShah
  • 309
  • 1
  • 6
  • 19
  • 1
    use the personNamesListView.notifyDataSetchange() after the insertion and deletion the item in list or update the items of list – Ravind Maurya Jan 22 '14 at 10:31
  • And when I type personNamesListView. there is no suggestions like notifyDataSetChanges(). – bShah Jan 22 '14 at 11:01
  • Sorry brother its traineeListAdapter.notifyDataSetChanged() – Ravind Maurya Jan 22 '14 at 11:03
  • Still it does not show any hint like that. it just shows; notify() and notifyAll(); – bShah Jan 22 '14 at 11:13
  • I am idiot. I made variable like: private ListAdapter traineeListAdapter; And declare on the onCreate() {traineeListAdapter = new ArrayAdapter}. Now I changed and able to get traineeListAdapter.notifyDataSetChanged. But still it is not working. :( – bShah Jan 23 '14 at 08:13

3 Answers3

1

You should call traineeListAdapter.notifyDataSetChanged() whenever you update your ArrayList representing the items in the ListView.

Kent Hawkings
  • 2,793
  • 2
  • 25
  • 30
0

There's a similar question here that can give you some help.

Although I've accomplished something similar using

yourlistview.invalidateViews() after changing the data to show in the listview

when notifyDataSetChanged() didn't work.

EDIT:

After making all the operations in the data that I want to show i just set the adapter and try to refresh my listview by calling invalidateViews().

selectedStrings = new ArrayList<String>(typeFilterStrings);
adapter.setArrayResultados(selectedStrings);
listTypeFilter.invalidateViews();

It's not obligatory to set the adapter again in my case worked.

Community
  • 1
  • 1
T.V.
  • 793
  • 12
  • 33
  • I am sorry to say that my listview is populated with array of items not with single items in each view. And I do not have interface to selectItem or item cannot be clickable. :( – bShah Jan 22 '14 at 11:09
  • I have search box using autocomplete text view. When user finds himself he clicks the dropdown string of autocomplete and all the data is redirected to the form from database. There he can edit his data and update to database. – bShah Jan 22 '14 at 11:18
  • But do you query the database every time you use the search box? I'm having trouble understanding how the app works sorry. – T.V. Jan 22 '14 at 11:35
  • Yeah I query every time, while searching, I made somethng using if else statement . if user finds himself-> it returns the person_id and if he does not find, I pass id like(-1). You know in database there is no id with -1. Then it pass empty string to form to add new user. – bShah Jan 22 '14 at 11:41
  • So if you edit and save in database you should retrieve saved data from database. Are you certain you've made the database save correctly? make some log instead of populating the listview with your results. – T.V. Jan 22 '14 at 11:48
  • Yeah my database has been saved correctly. I am sure about it. The edited values are saved in database correctly, but only problem is that I cannot see them automatically in my listview after I click the submit button. – bShah Jan 22 '14 at 11:52
  • Ok I try to make log. – bShah Jan 22 '14 at 11:53
  • after submitting the values try to update the adapter using the method traineeListAdapter.notifyDataSetChanged() or the listview using yourlistview.invalidateViews() Otherwise I suggest to repopulate the array again although its not a good solution... – T.V. Jan 22 '14 at 11:56
  • My button is in another Activity class. So I do this in there? – bShah Jan 22 '14 at 11:59
  • And it does not show any hint like that. it just shows; notify() and notifyAll(); – bShah Jan 22 '14 at 12:00
  • Sorry no progress at all :( – bShah Jan 22 '14 at 12:04
  • Why don't you load the activity you want after click on the button... that will force the array and the adapter to load the data from the database, that data will be updated.. – T.V. Jan 22 '14 at 12:05
  • That's what I am doing. It works for the inserting new user but not for updating user. I finish() the formActivity where user edits or insert himself and after click the submit button it directs directly to this activity where the lists are shown. Now I am tired. I am thinking to extend baseAdapter. And let's see what happens. – bShah Jan 22 '14 at 12:12
  • Make sure after you do finish() in the form the activity onResume() gets called. Try to debug that. – T.V. Jan 22 '14 at 12:14
  • Yeah it does, onResume() gets called. – bShah Jan 22 '14 at 12:22
  • I am idiot. I made variable like: private ListAdapter traineeListAdapter; And declare on the onCreate() {traineeListAdapter = new ArrayAdapter}. Now I changed and able to get traineeListAdapter.notifyDataSetChanged. But still it is not working. :( – bShah Jan 23 '14 at 08:10
0

use like this:

Create an instance of your custom adapter, so you can use it anywhere you like...

  public class ScoreList extends SherlockFragmentActivity {

    private ListView listViewScore;

    private ScoreListAdapter adapter;

    static List<Score> listScore = new ArrayList<Score>();
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.score_list);
        ctx = this;
        listScore = dbh.getAllScores();

        listViewScore = (ListView) findViewById(R.id.score_list);

        adapter = new ScoreListAdapter(ctx, R.layout.score_row_item, listScore);
        listViewScore.setAdapter(adapter);

((BaseAdapter) listViewScore.getAdapter()).notifyDataSetChanged(); 

    }
    }

By the way, if your listScore array is already loaded, then you do not need to use

adapter.notifyDatasetChanged();

Ravind Maurya
  • 977
  • 15
  • 24
  • If I am really understood. I cannot use this adapter.notifyDatasetChanged(); in my case because my listview is populated directly from the array of list. See my edited question. Can I really use this in my case? – bShah Jan 22 '14 at 11:34
  • brother you can use this method on adapter – Ravind Maurya Jan 22 '14 at 11:41
  • after personNamesListView.setAdapter(traineeListAdapter); use traineeListAdapter.notifyDatasetChanged(); – Ravind Maurya Jan 22 '14 at 11:42
  • @user3180746 it doesn`t matter your data is populated from anywhere – Ravind Maurya Jan 22 '14 at 11:43
  • Sorry friend. I can use this method if I use like this way: **((BaseAdapter) traineeListAdapter).notifyDataSetChanged();** But still it is not working. – bShah Jan 22 '14 at 11:48
  • I think I can use this method only I extend my adapter to BaseAdapter. – bShah Jan 22 '14 at 11:49
  • I am idiot. I made variable like: private ListAdapter traineeListAdapter; And declare on the onCreate() {traineeListAdapter = new ArrayAdapter}. Now I changed and able to get traineeListAdapter.notifyDataSetChanged. But still it is not working. :( – bShah Jan 23 '14 at 08:17
  • @user3180746 brother when modifying your adapter by insertion or deletion then apply the traineeListAdapter.notifyDataSetChanged() it will work definately. – Ravind Maurya Jan 23 '14 at 08:28
  • Code hint please. I could not get what you are saying. In the code?? personNamesListView = (ListView) findViewById(R.id.traineeslist); traineeList = currentTraining.getTraineeArrayList(); traineeAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, traineeList); personNamesListView.setAdapter(traineeAdapter); traineeAdapter.notifyDataSetChanged(); – bShah Jan 23 '14 at 08:37
  • @user3180746 please paste your code how update your list and i have edited my answer please look it – Ravind Maurya Jan 23 '14 at 09:29
  • @user3180746 in this method after the insertion or deletion call again traineeList = currentTraining.getTraineeArrayList() traineeAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, traineeList); personNamesListView.setAdapter(traineeAdapter); traineeAdapter.notifyDataSetChanged(); or it call in onresume method – Ravind Maurya Jan 23 '14 at 09:37
  • I tried calling that in On resume method. It did not work. I try inside the storeToDb() method. Let's see – bShah Jan 23 '14 at 10:03
  • it does not help as well :( – bShah Jan 23 '14 at 10:16
  • @user3180746 onresume method works only if return back on this screen. i was thinking you are updating your db from any other acticity – Ravind Maurya Jan 23 '14 at 10:17
  • OnResume is working . I debugged and checked as well. Yeah I am updating my db from another activity. but the method is in model class, for updating. While inserting, it works perfectly but not while updating. – bShah Jan 23 '14 at 10:22