Data storage and interface display based on Android Application Development (3): android Application Development

Source: Internet
Author: User

Data storage and interface display based on Android Application Development (3): android Application Development
Generate XML file backup text message

  • Create several virtual text message objects that exist in the list
  • Backup Data is usually backed up to the SD card
Concatenate strings using StringBuffer
  • Append all nodes of the xml file to the sb object

    Sb. append ("<? Xml version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?> "); // Add the Start Node sb. append (" <smss> ") of smss ");.......
  • Write sb to the output stream

Use the XMl serializer to generate an xml file
  • Get the xml serializer object

    XmlSerializer xs = Xml.newSerializer();
  • Set the output stream for the serializer

    File file = new File (Environment. getExternalStorageDirectory (), "backupsms. xml "); FileOutputStream fos = new FileOutputStream (file); // specify the output stream xs for the serializer. setOutput (fos, "UTF-8 ");
  • Start generating xml file

    xs.startDocument("utf-8", true);xs.startTag(null, "smss");......
Pull parses xml files
  • First, write an xml file to save some weather information.
Get xml file
    InputStream is = getClassLoader().getResourceAsStream("weather.xml");
Get pull parser
    XmlPullParser xp = Xml.newPullParser();
Start Parsing
  • Obtains the event type of the current node where the pointer is located.

    int type = xp.getEventType();
  • There are five main types of events

    • START_DOCUMENT: Event Type of the xml Header
    • END_DOCUMENT: event type at the end of xml
    • START_TAG: The Event Type of the Start Node.
    • END_TAG: Event Type of the End Node
    • TEXT: Event Type of the TEXT node
  • If the retrieved event type is not END_DOCUMENT, the parsing is not complete. If yes, the parsing is complete and the while loop ends.

    while(type != XmlPullParser.END_DOCUMENT)
  • When parsing to different nodes, we need to perform different operations, so we can determine the name of the current node.

    • When it is parsed to the Start Node of weather, a new list is generated.
    • When it is parsed to the Start Node of the city, the city object is created to save the text to be parsed more conveniently.
    • When the node starts to be parsed to name, get the text content of the next node. The same is true for temp and pm.

      Case XmlPullParser. START_TAG: // get the name of the current node if ("weather ". equals (xp. getName () {citys = new ArrayList <City> ();} else if ("city ". equals (xp. getName () {city = new City ();} else if ("name ". equals (xp. getName () {// obtain the text String name = xp for the next node of the current node. nextText (); city. setName (name);} else if ("temp ". equals (xp. getName () {String temp = xp. nextText (); city. setTemp (temp);} else if ("pm ". equals (xp. getName () {String pm = xp. nextText (); city. setPm (pm);} break;
  • When it is resolved to the End Node of the city, it means that all the three subnodes of the city have been parsed, and the city object is added to the list

    case XmlPullParser.END_TAG:    if("city".equals(xp.getName())){            citys.add(city);    }
  • Black box testing
    • Test logical business
  • White box testing

    • Test logic method
  • Based on test Granularity

    • Method test: function test
    • Unit test
    • Integration test: integration test
    • System test: system test
  • Based on test Brute Force

    • Smoke test: smoke test
    • Stress test: pressure test
Unit Test junit
  • Define a class that inherits AndroidTestCase. Define a method in the class to test this method.

  • When specifying the command set, targetPackage specifies the package name of the application you want to test.

    <instrumentation android:name="android.test.InstrumentationTestRunner"android:targetPackage="com.ibky.junit"></instrumentation>
  • Define the class library used

    <uses-library android:name="android.test.runner"></uses-library>
  • The role of assertion to check whether the running result is consistent with the expectation

  • If an application exception occurs, it is thrown to the test framework.
SQLite Database
  • Lightweight relational databases
  • The api required to create a database: SQLiteOpenHelper

    • You must define a constructor:

      // Arg1: name of the database file // arg2: cursor factory // arg3: database version public MyOpenHelper (Context context, String name, CursorFactory factory, int version ){}
    • The onCreate method is called when the database is created.
    • The onUpgrade method is called during Database Upgrade.
Create a database
// Create the OpenHelper object MyOpenHelper oh = new MyOpenHelper (getContext (), "person. db ", null, 1); // obtain the database object. If the database does not exist, create and obtain the database first. If yes, obtain SQLiteDatabase db = oh. getWritableDatabase ();
  • GetWritableDatabase (): Open a database that can be read or written.
  • GetReadableDatabase (): Open the read-only database when the disk space is insufficient. Otherwise, the read/write database can be opened.
  • Create a table when creating a database

    public void onCreate(SQLiteDatabase db) {    // TODO Auto-generated method stub    db.execSQL("create table person (_id integer primary key autoincrement, name char(10), phone char(20), money integer(20))");}
SQL statements for adding, deleting, modifying, and querying databases
  • Insert into person (name, phone, money) values ('zhang san', '123', 159874611 );
  • Delete from person where name = 'Li si' and _ id = 4;
  • Update person set money = 6000 where name = 'Li si ';
  • Select name, phone from person where name = 'zhang san ';
Execute SQL statements to add, delete, modify, and query
// Insert db.exe cSQL ("insert into person (name, phone, money) values (?, ?, ?); ", New Object [] {" zhangsan ", 15987461,750 00}); // query Cursor cs = db. rawQuery ("select _ id, name, money from person where name = ?; ", New String [] {" James "});
  • This method is called before the test method is executed.

    Protected void setUp () throws Exception {super. setUp (); // obtain the virtual context object oh = new MyOpenHelper (getContext (), "people. db ", null, 1 );}
Use APIs for addition, deletion, modification, and query
  • Insert

    // Save the data to be stored in the database in the form of key-value pairs ContentValues cv = new ContentValues (); cv. put ("name", "Liu Neng"); cv. put ("phone", 1651646); cv. put ("money", 3500); // The returned value is the primary key of the modified row. If an error occurs,-1 long I = db is returned. insert ("person", null, cv );
  • Delete

    // The returned value is the number of deleted rows int I = db. delete ("person", "_ id =? And name =? ", New String [] {" 1 "," James "});
  • Modify

    ContentValues cv = new ContentValues (); cv. put ("money", 25000); int I = db. update ("person", cv, "name =? ", New String [] {" Zhao Si "});
  • Query

    // Arg1: The field to be queried // arg2: Query condition // arg3: The placeholder for filling the query condition Cursor cs = db. query ("person", new String [] {"name", "money"}, "name =? ", New String [] {" zhangsan "}, null); while (cs. moveToNext () {// obtain the index value of the specified column String name = cs. getString (cs. getColumnIndex ("name"); String money = cs. getString (cs. getColumnIndex ("money"); System. out. println (name + ";" + money );}
  • Ensure that multiple SQL statements either succeed or fail at the same time
  • The most common case: bank transfers
  • Transaction api

    Try {// enable transaction db. beginTransaction ();........... // set the db for successful transaction execution. setTransactionSuccessful ();} finally {// close the transaction // if the transaction has been set to run successfully, the SQL statement takes effect; otherwise, the db does not take effect. endTransaction ();}
Display database data to the screen ListView
  • Is used to display the entries of a row
  • MVC Structure
    • M: model layer, data to be displayed ---- people set
    • V: view layer. The user-viewed interface is ListView.
    • C: control layer, how to display operation data ---- adapter object
  • Each entry is a View object.
  • Two methods that must be implemented

    • First

      // The system calls this method to obtain the number of data records on the model layer @ Overridepublic int getCount () {return people. size ();}
    • Second

      // The system calls this method to obtain the View object to be displayed to ListView // position: the position of the data corresponding to the return View object in the Set @ Overridepublic View getView (int position, view convertView, ViewGroup parent) {System. out. println ("getView method call" + position); TextView TV = new TextView (MainActivity. this); // get the Person p = people element in the set. get (position); TV. setText (p. toString (); // return the TextView object, which will become the ListView entry return TV ;}
  • The number of entries displayed on the screen, and the getView method will be called several times. When the screen slides down, getView will continue to be called, and more View objects will be created and displayed on the screen.
Entry Cache
  • When an entry is displayed on the screen, the system caches the entry to the memory. When the entry enters the screen again, the system uses the cached entry as the convertView parameter when calling getView again, however, the input entry is not necessarily the previously cached entry. That is, when the system calls the getView method to obtain the first entry, it is possible to pass in the cache of any entry.

Related Article

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: 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.