Question

I'm getting an app together that basically displays database information nicely.

Main activity:

public class MainActivity extends FragmentActivity {
    public static List<Entry> entryTitles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MySQLiteHelper db = new MySQLiteHelper(this);
        entryTitles= db.getEntryTitles();
        .....
    }
    ....
}

Fragment for navigation drawer

public class PositionsFrag extends Fragment {
    public static EntryListAdaptor entryAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        int i = getArguments().getInt(ARG_ENTRY_NUMBER);
        switch(i){
            case 0:
                entryAdapter = new EntryListAdapter(getActivity(), MainActivity.entryTitles);
                lv.setAdapter(entryAdapter);
                break;
            .....
         }
     }
}

And finally, clicking on one of the action bar buttons opens a new activity to allow the user to add fields to a new entry. The 'done' action bar button in this new activity (creatively called NewActivity.java) should - in theory - create a new Entry object, add this new object into the Entries database, store the first element of each entry as a string into a new list and notify the entryAdapter that the List has been updated.

public class NewActivity extends Activity {
    db = new MySQLiteHelper(this);

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_done:
                db.newEntry(new Entry(title, date, location));
                MainActivity.entryTitles= db.getEntryTitles();
                PositionsFrag.entriesAdapter.notifyDataSetChanged();
                Toast.makeText(getApplicationContext(), db.printFirstTitle(), Toast.LENGTH_SHORT).show();
                finish();
             ....
             }
         }
     }

When I run this the toast correctly displays the first entry's title field (showing that the database is at least getting the new entry and that I have successfully written an SQLite read function) but the ListView in the PositionFragment never changes.

Any guidance on how to get this to work or suggestions of better structure would be greatly appreciated.

Cheers!

Was it helpful?

Solution

It looks like you are trying to refresh an UI element owned by another Activity (PositionsFrag.entriesAdapter.notifyDataSetChanged();), which is something you shouldn't do. You can start NewActivity with startActivityForResult() and wait for the add result in onActivityResult(), where you can safely call entriesAdapter.notifyDataSetChanged();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top