java - ANDROID - Populate custom ListView with Database on Fragment -


i have custom listview , database, i'm trying populate listview database, not work.

my code:

public class mainactivity extends listfragment  {      public sql mydbhelper;     public sqlitedatabase db = null;     public list<string> mostrar, mostrar2;     adaptadortitulares adapter;     public listview list;      @override     public view oncreateview(layoutinflater inflater, viewgroup container,             bundle savedinstancestate) {          // if extending activity         view root = inflater.inflate(r.layout.activity_main, container, false);           try {             mydbhelper = new sql(getactivity());             mydbhelper.createdatabase(getactivity());          } catch (exception e) {         }         new threadbd().execute(); list = (listview) root.findviewbyid(android.r.id.list);  list.setonitemclicklistener(new onitemclicklistener() {         @override         public void onitemclick(adapterview<?> arg0, view arg1, int posicion, long arg3) {              string bebida=mostrar.get(posicion);             string precio=mostrar2.get(posicion);              //toast.maketext(getapplicationcontext(), "el precio es: " + precio + "y la bebida es: " + bebida, toast.length_long).show();         }         });           return root;     }// end oncreate   class adaptadortitulares extends baseadapter {          private activity mactivityact;         private layoutinflater minflater;         private arraylist<titular> mlitems;           public adaptadortitulares(activity a, arraylist<titular> it) {             try {                 mactivityact = a;                 mlitems = it;                 minflater = (layoutinflater) mactivityact                         .getsystemservice(context.layout_inflater_service);             } catch (exception e) {              }         }          public class vistah {              public textview nombree;             public textview grupoo;         }          @override         public int getcount() {              return mlitems.size();         }          @override         public object getitem(int position) {             return position;         }          @override         public long getitemid(int position) {             return position;         }          @override         public view getview(int position, view convertview, viewgroup parent) {             view vi = convertview;             vistah vh = null;              if (vi == null) {                 vi = minflater.inflate(r.layout.target_item, null);                 vh = new vistah();                 vh.nombree = (textview) vi.findviewbyid(r.id.item_title);                 vh.grupoo = (textview) vi.findviewbyid(r.id.item_counter);                  vi.settag(vh);             }              vh = (vistah) vi.gettag();              titular notice = mlitems.get(position);             vh.nombree.settext(notice.getdate());             vh.grupoo.settext(notice.gettitle());              return vi;         }          @override         public void unregisterdatasetobserver(datasetobserver observer) {             if (observer != null) {                 super.unregisterdatasetobserver(observer);             }         }      }      private class threadbd extends asynctask<void, void, void> {          @override         protected void doinbackground(void... params) {              mydbhelper.opendatabase();              db = mydbhelper.getreadabledatabase();              cursor c = db.rawquery("select id lista order id desc",                     null);             c.movetofirst();              int num = c.getint(0);                mostrar = new arraylist<string>(num);             mostrar2 = new arraylist<string>(num);               (int = 0; <= num; i++) {                  cursor d = db.rawquery(                         "select nombre, precio lista id=" + + "",                         null);                  if (d.movetofirst()) {                      mostrar.add(d.getstring(0));                     mostrar2.add(string.valueof(d.getdouble(1)));                  }              }// fin              return null;         }// end inbackground          protected void onpostexecute(void result) {              titular titular;             arraylist<titular> mlist = new arraylist<titular>();              (int = 0; < mostrar.size(); i++) {                 try {                     titular = new titular(mostrar.get(i), mostrar2.get(i));                     mlist.add(titular);                 } catch (exception e) {                 }                  adaptadortitulares actualizaadapter=new adaptadortitulares(getactivity(), mlist);                 list.setadapter(actualizaadapter);              }         }     } } 

titular.java

public class titular {      private string date;     private string title;      public titular(string date, string title) {         // recibe el nombre de la canciĆ³n, grupo y su tiempo         this.date = date;         this.title = title;     }       public string getdate() {         return date;     }      public void setdate(string date) {         this.date = date;     }      public string gettitle() {         return title;     }      public void settitle(string title) {         this.title = title;     } } 

sql.java

public class sql extends sqliteopenhelper {     private static string db_path = "/data/data/com.example.listprueba/databases/";      private static string db_name = "prueba";      private final context mycontext;     private sqlitedatabase mydatabase;      public sql(context context)     {         super(context, db_name, null, 1);         this.mycontext = context;     }      public void createdatabase(context contexto) throws ioexception     {         boolean dbexist = checkdatabase();          if (dbexist)         {         } else         {             this.getreadabledatabase();             try             {                 copydatabase();              } catch (ioexception e)             {                 throw new error("error copiado base de datos");             }         }     }      private boolean checkdatabase()     {         sqlitedatabase checkdb = null;         try         {             string mypath = db_path + db_name;             checkdb = sqlitedatabase.opendatabase(mypath, null, sqlitedatabase.open_readonly);         } catch (sqliteexception e)         {         }         if (checkdb != null)         {             checkdb.close();         }         return checkdb != null ? true : false;     }      private void copydatabase() throws ioexception     {          inputstream myinput = mycontext.getassets().open(db_name);          string outfilename = db_path + db_name;          outputstream myoutput = new fileoutputstream(outfilename);           byte[] buffer = new byte[1024];         int length;         while ((length = myinput.read(buffer)) > 0)         {             myoutput.write(buffer, 0, length);         }          // liberamos los streams         myoutput.flush();         myoutput.close();         myinput.close();      }      public void opendatabase() throws sqlexception     {         string mypath = db_path + db_name;         mydatabase = sqlitedatabase.opendatabase(mypath, null, sqlitedatabase.open_readonly);      }      public synchronized void close()     {         if (mydatabase != null)             mydatabase.close();          super.close();     }      @override     public void oncreate(sqlitedatabase db)     {      }      @override     public void onupgrade(sqlitedatabase db, int oldversion, int newversion)     {      } } 

activity_mail.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" >      <listview         android:id="@android:id/list"         android:layout_width="wrap_content"         android:layout_height="match_parent" >  </listview>  </linearlayout> 

target_item.xml

<?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="48dp"     android:background="#f3f3f3">       <!-- icon -->      <imageview          android:id="@+id/item_icon"          android:layout_width="32dp"          android:layout_height="32dp"          android:layout_alignparentleft="true"          android:layout_marginleft="8dp"          android:layout_marginright="8dp"          android:layout_margintop="8dp"          android:src="@drawable/ic_action_help"          />      <!-- title -->     <textview          android:id="@+id/item_title"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_torightof="@+id/item_icon"          android:layout_alignbaseline="@+id/item_counter"          android:textsize="18dp" />          <!-- counter -->         <textview             android:id="@+id/item_counter"             android:layout_width="50dp"             android:layout_height="32dp"             android:layout_alignparentright="true"             android:layout_marginright="8dp"             android:layout_margintop="8dp"             android:background="@drawable/rectangle"             android:gravity="center"             android:textcolor="#ffffff"             android:textsize="12sp"             android:textstyle="bold" />  </relativelayout> 

error

06-08 22:35:31.091: e/androidruntime(1470): fatal exception: main 06-08 22:35:31.091: e/androidruntime(1470): process: com.example.listprueba, pid: 1470 06-08 22:35:31.091: e/androidruntime(1470): java.lang.runtimeexception: unable instantiate activity componentinfo{com.example.listprueba/com.example.listprueba.mainactivity}: java.lang.classcastexception: com.example.listprueba.mainactivity cannot cast android.app.activity 06-08 22:35:31.091: e/androidruntime(1470):     @ android.app.activitythread.performlaunchactivity(activitythread.java:2121) 06-08 22:35:31.091: e/androidruntime(1470):     @ android.app.activitythread.handlelaunchactivity(activitythread.java:2245) 06-08 22:35:31.091: e/androidruntime(1470):     @ android.app.activitythread.access$800(activitythread.java:135) 06-08 22:35:31.091: e/androidruntime(1470):     @ android.app.activitythread$h.handlemessage(activitythread.java:1196) 06-08 22:35:31.091: e/androidruntime(1470):     @ android.os.handler.dispatchmessage(handler.java:102) 06-08 22:35:31.091: e/androidruntime(1470):     @ android.os.looper.loop(looper.java:136) 06-08 22:35:31.091: e/androidruntime(1470):     @ android.app.activitythread.main(activitythread.java:5017) 06-08 22:35:31.091: e/androidruntime(1470):     @ java.lang.reflect.method.invokenative(native method) 06-08 22:35:31.091: e/androidruntime(1470):     @ java.lang.reflect.method.invoke(method.java:515) 06-08 22:35:31.091: e/androidruntime(1470):     @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:779) 06-08 22:35:31.091: e/androidruntime(1470):     @ com.android.internal.os.zygoteinit.main(zygoteinit.java:595) 06-08 22:35:31.091: e/androidruntime(1470):     @ dalvik.system.nativestart.main(native method) 06-08 22:35:31.091: e/androidruntime(1470): caused by: java.lang.classcastexception: com.example.listprueba.mainactivity cannot cast android.app.activity 06-08 22:35:31.091: e/androidruntime(1470):     @ android.app.instrumentation.newactivity(instrumentation.java:1061) 06-08 22:35:31.091: e/androidruntime(1470):     @ android.app.activitythread.performlaunchactivity(activitythread.java:2112) 06-08 22:35:31.091: e/androidruntime(1470):     ... 11 more 

do know can error? should change anything?, if extend listactivity class works perfectly.

i dont know how can extends fragments instead listactivity....

try having mainactivity extend fragmentactivity , create new class listfragment can extend fragment. here can populate listview data db. check nice tutorial here >> http://www.vogella.com/tutorials/androidlistview/article.html#listfragments


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -