In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces Android how to achieve data storage management through the SQLite database, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
0 experimental environment
Write the relevant code and show the interface effect in Android Studio.
SQLiteStudio: a graphical tool for SQLite Database
Download URL: SQLiteStudio official website
1 interface display
2 function description
(1) it is necessary to implement an application that allows users to input and store data.
(2) it can realize the basic CRUD operation, delete, check and change the data.
(3) there should be input field and result display at the same time.
3 Design principle
SQLiteOpenHelper is an abstract tool class provided by Android, which is responsible for managing the creation and upgrade of the database. If we want to create a database, we need to customize a class that inherits SQLiteOpenHelper, and then overrides the abstract methods in it.
Where the DbHelper class inherits the SQLiteOpenHelper class. The table is created by executing the sql statement in the onCreate () method. The MyDAO class defines the method of adding, deleting, changing and querying the operation database, insert (), delete (), update (), select ()
4 core code 4.1 UI design
Activity_main.xml designs the main interface, which needs input field, operation button and result display, in which the result display is displayed by listView component.
Part of the code:
Design the item elements for the above listView components:
4.2 write about the Java class
(1) MainActivity class, which is used to initialize some variables and register components:
Core code: (only onCreate and displayRecords methods are shown here)
@ Overrideprotected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); myDAO = new MyDAO (this); / / create database access object if (myDAO.getRecordsNumber () = = 0) {/ / prevent repeated run-time insertion of record myDAO.insertInfo ("Wang Jiawei", 20); / / insert record myDAO.insertInfo ("knot", 19) / / insert record} initView (); initEvent (); displayRecords (); / / display record} public void displayRecords () {/ / display record method definition listView = (ListView) findViewById (R.id.listView); listData = new ArrayList (); Cursor cursor = myDAO.allQuery (); while (cursor.moveToNext ()) {int id=cursor.getInt (0) / / get the field value String name=cursor.getString (1); / / int age=cursor.getInt (2); @ SuppressLint ("Range") int age=cursor.getInt (cursor.getColumnIndex ("age")); / / recommend this method listItem=new HashMap (); / / you must create a new listItem.put ("_ id", id) in the loop body / / the first parameter is the key name, and the second parameter is the key value listItem.put ("name", name); listItem.put ("age", age); listData.add (listItem) / / add a record} listAdapter = new SimpleAdapter (this, listData, R.layout.list_item, / / self-created list item layout new String [] {"_ id", "name", "age"}, new int [] {R.id.TVICIDR. / / Application adapter listView.setOnItemClickListener (new AdapterView.OnItemClickListener () {/ / list item listener @ Override public void onItemClick (AdapterView parent, View view, int position, long id) {Map rec= (Map) listAdapter.getItem (position); / / fetch record et_name.setText (rec.get ("name"). ToString ()) from the adapter / / refresh the text box et_age.setText (rec.get ("age"). ToString (); Log.i ("ly", rec.get ("_ id"). ToString ()); selId=rec.get ("_ id"). ToString (); / for modification and deletion}}) } (2) the DbHelper class is the SQLite database opening helper class, which is used to create and open the database and create data tables:
Core code:
Public class DbHelper extends SQLiteOpenHelper {public static final String TB_NAME = "friends"; / / Table name / / Construction method: the first parameter is the context, the second parameter library name, the third parameter is the cursor factory, and the fourth parameter is the version public DbHelper (Context context, String dbname, SQLiteDatabase.CursorFactory factory, int version) {super (context, dbname, factory, version) / / create or open database} @ Override public void onCreate (SQLiteDatabase db) {/ / create a table when it does not exist The first field is self-growing type db.execSQL ("CREATE TABLE IF NOT EXISTS" + TB_NAME + "(_ id integer primary key autoincrement," + "name varchar," + "age integer" + ")");} @ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {/ / execute the SQL command db.execSQL ("DROP TABLE IF EXISTS" + TB_NAME) OnCreate (db);}} (3) the operation of adding, deleting, querying and modifying the database is defined in the MyDAO class, so that the relevant API interface can be called directly in the main program file:
Core code:
/ / constructor, parameter is context object public MyDAO (Context context) {/ / the first parameter is context, the second parameter is database name dbHelper = new DbHelper (context, "test.db", null, 1);} / / query all records public Cursor allQuery () {myDb = dbHelper.getReadableDatabase (); return myDb.rawQuery ("select * from friends", null) } / / return public int getRecordsNumber () {myDb = dbHelper.getReadableDatabase (); Cursor cursor = myDb.rawQuery ("select * from friends", null); return cursor.getCount ();} / / insert record public void insertInfo (String name, int age) {myDb = dbHelper.getWritableDatabase (); ContentValues values = new ContentValues (); values.put ("name", name); values.put ("age", age) Long rowid = myDb.insert (DbHelper.TB_NAME, null, values); if (rowid = =-1) Log.i ("myDbDemo", "data insertion failed!") ; else Log.i ("myDbDemo", "data inserted successfully!" + rowid);} / delete record public void deleteInfo (String selId) {String where = "_ id=" + selId; int i = myDb.delete (DbHelper.TB_NAME, where, null); if (I > 0) Log.i ("myDbDemo", "data deleted successfully!") ; else Log.i ("myDbDemo", "data not deleted!") ;} / / the third parameter in the public void updateInfo (String name, int age, String selId) {/ / method is used to modify the selected record ContentValues values = new ContentValues (); values.put ("name", name); values.put ("age", age); String where = "_ id=" + selId; int i = myDb.update (DbHelper.TB_NAME, values, where, null) / / the functions of the above lines of code can be implemented with the following line of code / / myDb.execSQL ("update friends set name =?, age =? Where _ id =? ", new Object [] {name,age,selId}); if (I > 0) Log.i (" myDbDemo "," data updated successfully! ") ; else Log.i ("myDbDemo", "data not updated!") ;} (4) use the graphical tool SQLiteStudio of the SQLite database to view the table data in the data file created in the application:
Note: the created database is located in: / data/data/ package name / databases/ directory
Finally, use the graphical tool SQLiteStudio of SQLite database to import the saved db file into SQLiteStudio to view the table data in the data file created in the application.
Structure of the data table:
Data in the datasheet:
Thank you for reading this article carefully. I hope the article "how Android implements data storage management through SQLite database" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.