Android database read data display [5]

Source: Internet
Author: User

2016-12-1 Course Content

Learned about Android Database upgrade, downgrade, create yesterday

Today, read the data from the database table and display it on the phone screen.

The following code is the code for Mainactivity.java

 PackageCOM.EXAMPLE.WINXINMFF;Importjava.sql.SQLException;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importandroid.app.Activity;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.AdapterView;ImportAndroid.widget.AdapterView.OnItemClickListener;ImportAndroid.widget.ListView;ImportAndroid.widget.SimpleAdapter;ImportAndroid.widget.Toast;ImportCom.example.entity.Message;ImportCOM.EXAMPLE.WINXINMFFSQL.R;ImportCom.j256.ormlite.dao.Dao; Public classMainactivityextendsActivity {PrivateSimpleadapter sa;//is a list adapter in Android that is primarily used to do some simple list adaptation    PrivateListView LV; PrivateList<message> messagelist =NewArraylist<message>(); Privatelist<map<string, object>> messageList2 =NewArraylist<map<string, object>>(); PrivateList<message> MessageList3;//Demo for Ormlite//look at the name is Databasehelper, the database assistant means, this is a class in itself. //contains the database connection, closed, if there is an extension may contain the basic database JDBC operation method is to simplify the deletion and modification of some methods.     PrivateDatabasehelper Db_helper; //This method is called when it is first created.     protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.weixin); //This 3 line of code is used to create the table structure and initialize the dataMydatabaseopenhelper helper =Newmydatabaseopenhelper (MainActivity1. This); Sqlitedatabase DB=helper.getwritabledatabase ();        Db.close (); LV=(ListView) Findviewbyid (R.ID.LISTVIEW1); SA=NewSimpleadapter ( This, MessageList2,//Data is a data mix coupled to the interfaceR.layout.listview_item_layout,NewString[] {"Tou",                        "UserName", "Lastmessage", "datetime"},//from Never come                New int[] {r.id.imageview1, r.id.tv_username, R.id.tv_lasmessage, r.id.tv_datetime}//to get there.        );        Lv.setadapter (SA); Lv.setonitemclicklistener (NewOnitemclicklistener () { Public voidOnitemclick (adapterview<?>Parent, view view,intPositionLongID) {MAP<string, object> item =Messagelist2.get (position); Item.put ("UserName", "Zhao Benshan" +position);            Sa.notifydatasetchanged ();    }        }); }    //UI present in front of you    protected voidOnresume () {LOG.I ("OK", "Onresume, Interface appears"); //using OrmliteDb_helper =NewDatabasehelper ( This); Dao<message, integer> Message_dao =Db_helper.getmessagedao (); Try{messageList3=Message_dao.queryforall (); //log.i ("Ormlite", "Number of record strips:" +messagelist3.size ());String T = "Number of record bars:" +messagelist3.size (); Toast.maketext ( This, T, Toast.length_long). Show (); } Catch(SQLException e) {String T= "Remember error:" +E.getmessage (); Toast.maketext ( This, T, Toast.length_long). Show (); }        //analog Read database or Internet         for(inti = 0; I < messagelist3.size (); i++) {Message P=NewMessage (); P.SETTOU1 ("XXX"); P.setusername ("Not open to high cohesion"); P.setlastmessage ("An anonymous inner class is an inner class without a name. Anonymous inner class is an inner class without a name."); P.setdatetime ("11.11"); Messagelist.add (p);//last week//define a mix of interfaces and data, one item for a row of recordsmap<string, object> item =NewHashmap<string, object>(); //one row of records, containing multiple controlsItem.put ("Tou", R.drawable.a);//AvatarItem.put ("UserName", Messagelist3.get (i). GetUserName () + i);//nameItem.put ("Lastmessage", Messagelist3.get (i). Getlastmessage ());//contentItem.put ("datetime", Messagelist3.get (i). GetDateTime ());//TimeMessagelist2.add (item);//Add to Collection        }        Super. Onresume (); }    //The UI disappears completely in front of you, completely covered by another process    protected voidOnPause () {LOG.I ("OK", "OnPause, abandoned"); Db_helper.close ();// ?? Do you want it anyway?         Super. OnPause (); }}
mainactivity

Database helper Classes

 PackageCOM.EXAMPLE.WINXINMFF;Importjava.sql.SQLException;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;ImportCom.example.entity.Message;ImportCom.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;ImportCom.j256.ormlite.dao.Dao;ImportCom.j256.ormlite.support.ConnectionSource; Public classDatabasehelperextendsOrmlitesqliteopenhelper {Private Static FinalString db_name = "mydata.db";//Database name    Private Static Final intVersion = 1;//Database Version//define member variables for each table, one of the functions: Close helper, all DAO object cleanup    PrivateDao<message, integer>Messagedao;  PublicDao<message, integer>Getmessagedao () {if(Messagedao = =NULL) {            Try{Messagedao= Getdao (Message.class); } Catch(SQLException e) {e.printstacktrace (); }        }        returnMessagedao; }             PublicDatabasehelper (Context context) {Super(Context, Db_name,NULL, version); }    /** 1. This method, which does not execute automatically, needs to be performed manually because it is not a callback function * 2. Finally, do not call yourself, because only 1 times should be performed*/     Public voidonCreate (sqlitedatabase arg0, Connectionsource arg1) {}/** This method, which does not execute automatically, requires manual execution because it is not a callback function*/     Public voidOnupgrade (sqlitedatabase arg0, Connectionsource arg1,intArg2,intArg3) {    }        protectedObject Clone ()throwsclonenotsupportedexception {if(Messagedao! =NULL) {Messagedao=NULL; }        return Super. Clone (); }}
Databasehelper

Display effect:

And yesterday with the command query is the result is the same (figure is yesterday)

Tell me what's inside.

Line 41 is the new Mydatabaseopenhelper () method that defines itself

43-row Getwritabledatabase () method to open a database in read-write mode

44 Line Close Resource

  Android uses the Getwritabledatabase () and Getreadabledatabase () methods to obtain a sqlitedatabase instance that is used to manipulate the database.

(The Getwritabledatabase () method is called in the Getreadabledatabase () method)

where the Getwritabledatabase () method opens the database in read-write mode,

Once the database is full of disk space, the database is read-only and cannot be written, and an error occurs if the Getwritabledatabase () method is used.

If the user goes back to your activity from pause (paused), the system resume the activity and calls the Onresume () method.

Pause (pause) your activity

When the system calls the activity's OnPause (), though technically your activity is visible,

But more often this also indicates that the user will leave the activity, and then your activity will go into the stop state.

Pause (pause) and resume (re-return) of activity's life cycle

Http://www.jcodecraeer.com/a/anzhuokaifa/developer/2013/0715/1439.html

Android database read data display [5]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.