Android Update Mainactivity List View after popup Dialog updates database -


i have listview on mainactivity showing items database. have add button in action bar. when add button clicked on dialog pops , user fills out fields new item , click "add" , adds item database. problem listview on mainactivity doesn't update show new item. can close app , reopen , see new item. doesn't update immediatly. (same problem deleting item, delete happens onlongpress)

mainactivity.java

package blah.blah.blah  import android.app.alertdialog; import android.app.dialog; import android.app.dialogfragment; import android.content.contentvalues; import android.content.dialoginterface; import android.database.cursor; import android.database.sqlite.sqlitedatabase; import android.os.bundle; import android.support.v4.app.fragment; import android.support.v4.app.fragmentactivity; import android.support.v4.app.fragmentmanager; import android.support.v4.app.fragmentpageradapter; import android.support.v4.view.viewpager; import android.util.log; import android.view.contextmenu; import android.view.contextmenu.contextmenuinfo; import android.view.layoutinflater; import android.view.menu; import android.view.menuitem; import android.view.view; import android.view.viewgroup; import android.widget.adapterview; import android.widget.arrayadapter; import android.widget.edittext; import android.widget.listview; import android.widget.spinner; import android.widget.textview;  public class initactivity extends fragmentactivity {      sectionspageradapter msectionspageradapter;      viewpager mviewpager;      @override     protected void oncreate(bundle savedinstancestate) {         // gets data repository in write mode         playersdbhelper mdbhelper = new playersdbhelper(getbasecontext());         sqlitedatabase db = mdbhelper.getwritabledatabase();           super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_init);          // create adapter return fragment each of 3         // primary sections of app.         msectionspageradapter = new sectionspageradapter(                 getsupportfragmentmanager());          // set viewpager sections adapter.         mviewpager = (viewpager) findviewbyid(r.id.pager);         mviewpager.setadapter(msectionspageradapter);      }//end oncreate()      @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.init, menu);         return true;     }      @override     public boolean onoptionsitemselected(menuitem item) {         // handle presses on action bar items         switch (item.getitemid()) {             case r.id.action_add:                 showaddplayerdialog();                 return true;             default:                 return super.onoptionsitemselected(item);         }     }      public void showaddplayerdialog() {         // create instance of dialog fragment , show         dialogfragment dialog = new addplayerdialog();         dialog.show(this.getfragmentmanager(), "addplayerfragment");     }      public class sectionspageradapter extends fragmentpageradapter {          public sectionspageradapter(fragmentmanager fm) {             super(fm);         }          @override         public fragment getitem(int position) {              if(position == 0) {                 fragment playersfragment = new playersfragment();                 return playersfragment;             } else if(position == 1){                 fragment otherfragment= new otherfragment();                 return otherfragment;             } else {                 fragment otherfragment2 = new otherfragment2();                 return otherfragment2;             }          }          @override         public int getcount() {             // show 3 total pages.             return 3;         }          @override         public charsequence getpagetitle(int position) {             locale l = locale.getdefault();             switch (position) {             case 0:                 return getstring(r.string.title_section1).touppercase(l);             case 1:                 return getstring(r.string.title_section2).touppercase(l);             case 2:                 return getstring(r.string.title_section3).touppercase(l);             }             return null;         }     }//end sectionspageradapter()       public static class playersfragment extends fragment {          public static final string arg_section_number = "section_number";         public int myfragmentid = 1;         private listview mylistview;         private string[] values;          public arrayadapter<string> adapter;            public playersfragment() {         }          @override         public view oncreateview(layoutinflater inflater, viewgroup container,                 bundle savedinstancestate) {              view rootview = inflater.inflate(r.layout.fragment_players,                     container, false);             mylistview = (listview) rootview.findviewbyid(r.id.mylistview);              registerforcontextmenu(mylistview);              playersdbhelper mdbhelper = new playersdbhelper(rootview.getcontext());             sqlitedatabase db = mdbhelper.getreadabledatabase();              // define projection specifies columns database             // use after query.             string[] projection = {                 playerentry._id,                 playerentry.column_name_id,                 playerentry.column_name_name,                 playerentry.column_name_position                 };             string selection = null;            //null return rows given table             string[] selectionargs = null;      //null should return data              // how want results sorted in resulting cursor             string sortorder =                     playerentry.column_name_name + " desc";               cursor c = db.query(                 playerentry.table_name,                   // table query                 projection,                               // columns return                 selection,                                // columns clause                 selectionargs,                            // values clause                 null,                                     // don't group rows                 null,                                     // don't filter row groups                 sortorder                                 // sort order                 );              values = new string[] {};              string array[] = new string[c.getcount()];             int = 0;              c.movetofirst();             while (c.isafterlast() == false) {                 array[i] = c.getstring(c.getcolumnindexorthrow(playerentry.column_name_name));                 i++;                 c.movetonext();             }              for(int x = 0; x < array.length ; x++){                 log.d("logan", "entry at:" + x + " " + array[x]);                 values = push(values, array[x]);             }              adapter = new arrayadapter<string>(this.getactivity(),                 android.r.layout.simple_list_item_1, values);             mylistview.setadapter(adapter);              return rootview;         }          private static string[] push(string[] array, string push) {             string[] longer = new string[array.length + 1];             (int = 0; < array.length; i++)                 longer[i] = array[i];             longer[array.length] = push;             return longer;         }          @override         public void oncreatecontextmenu(contextmenu menu, view v,             contextmenuinfo menuinfo) {           if (v.getid()==r.id.mylistview) {             adapterview.adaptercontextmenuinfo info = (adapterview.adaptercontextmenuinfo)menuinfo;             menu.setheadertitle(values[info.position]);             string[] menuitems = {"edit", "delete"};             (int = 0; i<menuitems.length; i++) {               menu.add(menu.none, i, i, menuitems[i]);             }           }         }          @override         public boolean oncontextitemselected(menuitem item) {             playersdbhelper mdbhelper = new playersdbhelper(getactivity());            final sqlitedatabase db = mdbhelper.getwritabledatabase();               adapterview.adaptercontextmenuinfo info = (adapterview.adaptercontextmenuinfo)item.getmenuinfo();             int menuitemindex = item.getitemid();             string[] menuitems = {"edit", "delete"};             string menuitemname = menuitems[menuitemindex];             string listitemname = values[info.position];              if(menuitemname.equalsignorecase("edit")) {              } else {                 //menuitemname === delete                 // define 'where' part of query.                 string selection = playerentry.column_name_name + " =? ";                  // specify arguments in placeholder order.                 string[] selectionargs = { listitemname };                  // issue sql statement.                 db.delete(playerentry.table_name, selection, selectionargs);                  adapter.notifydatasetchanged();             }             return true;         }       }      public static class otherfragment extends fragment {          public static final string arg_section_number = "section_number";          public otherfragment() {         }          @override         public view oncreateview(layoutinflater inflater, viewgroup container,                 bundle savedinstancestate) {             view rootview = inflater.inflate(r.layout.fragment_lineup,                     container, false);             return rootview;         }     }      public static class otherfragment2 extends fragment {          public static final string arg_section_number = "section_number";          public otherfragment2() {         }          @override         public view oncreateview(layoutinflater inflater, viewgroup container,                 bundle savedinstancestate) {             view rootview = inflater.inflate(r.layout.fragment_position,                     container, false);             return rootview;         }     }  } 

addplayerdialog.java

package blah.blah.blah;  import android.app.alertdialog; import android.app.dialog; import android.app.dialogfragment; import android.content.contentvalues; import android.content.dialoginterface; import android.database.sqlite.sqlitedatabase; import android.os.bundle; import android.text.editable; import android.util.log; import android.view.layoutinflater; import android.view.view; import android.widget.arrayadapter; import android.widget.baseadapter; import android.widget.edittext; import android.widget.listview; import android.widget.spinner;  public class addplayerdialog extends dialogfragment{      @override     public dialog oncreatedialog(bundle savedinstancestate) {          // gets data repository in write mode        playersdbhelper mdbhelper = new playersdbhelper(getactivity().getbasecontext());        final sqlitedatabase db = mdbhelper.getwritabledatabase();          alertdialog.builder builder = new alertdialog.builder(getactivity());         // layout inflater         final layoutinflater inflater = getactivity().getlayoutinflater();          // inflate , set layout dialog         // pass null parent view because going in dialog layout         final view view = inflater.inflate(r.layout.addplayerdialog, null);          final listview list = (listview)view.findviewbyid(r.id.mylistview);          builder.setview(view)         // add action buttons                .setpositivebutton(r.string.add, new dialoginterface.onclicklistener() {                    @override                    public void onclick(dialoginterface dialog, int id) {                        // sign in user ...                        edittext fname = (edittext) view.findviewbyid(r.id.editfirstname);                        editable firstname = fname.gettext();                         edittext lname = (edittext) view.findviewbyid(r.id.editlastname);                        editable lastname = lname.gettext();                         edittext number = (edittext) view.findviewbyid(r.id.playernumber);                        int num = integer.parseint(number.gettext().tostring());                         spinner spinner = (spinner) view.findviewbyid(r.id.positionspinner);                        string position = spinner.getselecteditem().tostring();                         // create new map of values, column names keys                        contentvalues values = new contentvalues();                        values.put(playerentry.column_name_id, num);                        values.put(playerentry.column_name_name, firstname + " " + lastname);                        values.put(playerentry.column_name_position, position);                         // insert new row, returning primary key value of new row                        long newrowid;                        newrowid = db.insert(                                playerentry.table_name,                                null,                                values);                        //**** here think change needs be! ****                         ((arrayadapter) list.getadapter()).notifydatasetchanged();                     }                })                .setnegativebutton(r.string.cancel, new dialoginterface.onclicklistener() {                    public void onclick(dialoginterface dialog, int id) {                        dialog.cancel();                    }                });          spinner spinner = (spinner) view.findviewbyid(r.id.positionspinner);         // create arrayadapter using string array , default spinner layout         arrayadapter<charsequence> adapter = arrayadapter.createfromresource(getactivity(),                 r.array.positions, android.r.layout.simple_spinner_item);         // specify layout use when list of choices appears         adapter.setdropdownviewresource(android.r.layout.simple_spinner_dropdown_item);         // apply adapter spinner         spinner.setadapter(adapter);          return builder.create();     } } 

addplayerdialog.xml

<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >      <edittext         android:id="@+id/editfirstname"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:ems="10"         android:hint="@string/fname" >          <requestfocus />     </edittext>      <edittext         android:id="@+id/editlastname"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:ems="10"         android:hint="@string/lname" />      <edittext         android:id="@+id/playernumber"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:ems="10"         android:hint="@string/playernumberhint"         android:inputtype="number" />      <spinner         android:id="@+id/positionspinner"         android:layout_width="match_parent"         android:layout_height="wrap_content" />  </linearlayout> 

i think inserted data db forgot call yourlistviewadapter.add method before calling notifydatasetchanged


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -