Data storage and interface presentation based on Android application development (III.)

Source: Internet
Author: User
Tags sqlite database

Generate an XML file backup SMS
    • Create a few virtual SMS objects that exist in list
    • Backup data is usually backed up to an SD card
Use StringBuffer to stitch strings
    • Append all nodes of the entire XML file into SB object

      sb.append("<?xml version=‘1.0‘ encoding=‘utf-8‘ standalone=‘yes‘ ?>");//添加smss的开始节点sb.append("<smss>");.......
    • Write SB into the output stream

      fos.write(sb.toString().getBytes());
To generate an XML file using an XML serializer
    • Get the XML Serializer object

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

      File file = new File(Environment.getExternalStorageDirectory(), "backupsms.xml");FileOutputStream fos = new FileOutputStream(file);//给序列化器指定好输出流xs.setOutput(fos, "utf-8");
    • To start generating an XML file

      xs.startDocument("utf-8", true);xs.startTag(null, "smss");......
Pull Parse XML file
    • Write an XML file yourself, save some weather information
Get the XML file
    InputStream is = getClassLoader().getResourceAsStream("weather.xml");
Get the pull parser.
    XmlPullParser xp = Xml.newPullParser();
Start parsing
  • Get the event type of the current node where the pointer is located

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

    • Event types for Start_document:xml headers
    • Type of event End_document:xml tail
    • Start_tag: Event type of the start node
    • End_tag: Event type for end node
    • Text: The event type of the literal node
  • If the obtained event type is not end_document, then the parsing is not complete, and if it is, the parsing is complete and the while loop ends

    while(type != XmlPullParser.END_DOCUMENT)
  • When we resolve to different nodes, we need to do different things, so we can judge the name of the current node.

    • When parsing to the start node of weather, the new list
    • When resolving to the start node of city, the city object is created and the object is created to make it easier to save the text that will be parsed
    • When parsing to the name start node, gets the text content of the next node, same as temp, PM

      case XmlPullParser.START_TAG://获取当前节点的名字    if("weather".equals(xp.getName())){        citys = new ArrayList<City>();    }    else if("city".equals(xp.getName())){        city = new City();    }    else if("name".equals(xp.getName())){        //获取当前节点的下一个节点的文本        String name = xp.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 resolving to the end node of city, it shows that the city's three child nodes have all been parsed, adding the city object to the list

    case XmlPullParser.END_TAG:    if("city".equals(xp.getName())){            citys.add(city);    }
Test
    • Black box test
      • Testing the logic Business
    • White box test

      • Test logic methods
    • According to the test grain size

      • Method Test: Function test
      • Unit Tested: Unit test
      • Integration test: Integration test
      • Systems Testing: System test
    • According to the level of testing violence

      • Smoke Test: Smoke test
      • Stress test: Pressure test
Unit Test JUnit
    • Define a class to inherit androidtestcase, define a method in the class, and test the method

    • When specifying the instruction set, Targetpackage specifies the package name of the app you want to test

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

      <uses-library android:name="android.test.runner"></uses-library>
    • The role of assertions, the detection of running results and the consistency of expectations

    • If an application has an exception, it is thrown to the test framework
SQLite database
    • Lightweight relational database
    • Api:sqliteopenhelper to use to create a database

      • You must define a construction method:

        //arg1:数据库文件的名字//arg2:游标工厂//arg3:数据库版本public MyOpenHelper(Context context, String name, CursorFactory factory, int version){}
      • Called when the database is created: OnCreate method
      • Called when the database is upgraded: Onupgrade method
Create a database
//创建OpenHelper对象MyOpenHelper oh = new MyOpenHelper(getContext(), "person.db", null, 1);//获得数据库对象,如果数据库不存在,先创建数据库,后获得,如果存在,则直接获得SQLiteDatabase db = oh.getWritableDatabase();
    • Getwritabledatabase (): Open a writable database
    • Getreadabledatabase (): Open read-only database when disk space is low, otherwise open read-write database
    • Create a table when you create 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))");}
Database additions and Deletions change SQL statements
    • INSERT into person (name, phone, money) VALUES (' Zhang San ', ' 159874611 ', 2000);
    • Delete from the person where name = ' John Doe ' and _id = 4;
    • Update person Set money = 6000 where name = ' John Doe ';
    • Select name, phone from person where name = ' Zhang San ';
Execute SQL statements to implement additions and deletions
    //插入    db.execSQL("insert into person (name, phone, money) values (?, ?, ?);", new Object[]{"张三", 15987461, 75000});    //查找    Cursor cs = db.rawQuery("select _id, name, money from person where name = ?;", new String[]{"张三"});
    • This method is called before the test method executes

      protected void setUp() throws Exception {    super.setUp();    //                  获取虚拟上下文对象    oh = new MyOpenHelper(getContext(), "people.db", null, 1);}
Use API to implement additions and deletions
    • Insert

      //以键值对的形式保存要存入数据库的数据ContentValues cv = new ContentValues();cv.put("name", "刘能");cv.put("phone", 1651646);cv.put("money", 3500);//返回值是改行的主键,如果出错返回-1long i = db.insert("person", null, cv);
    • Delete

      //返回值是删除的行数int i = db.delete("person", "_id = ? and name = ?", new String[]{"1", "张三"});
    • Modify

      ContentValues cv = new ContentValues();cv.put("money", 25000);int i = db.update("person", cv, "name = ?", new String[]{"赵四"});
    • Inquire

      //arg1:要查询的字段//arg2:查询条件//arg3:填充查询条件的占位符Cursor cs = db.query("person", new String[]{"name", "money"}, "name = ?", new String[]{"张三"}, null, null, null);while(cs.moveToNext()){    //                          获取指定列的索引值    String name = cs.getString(cs.getColumnIndex("name"));    String money = cs.getString(cs.getColumnIndex("money"));    System.out.println(name + ";" + money);}
Transaction
    • Ensure that multiple SQL statements either succeed at the same time or fail at the same time
    • Most common case: bank transfer
    • Transaction API

      try {    //开启事务    db.beginTransaction();    ...........    //设置事务执行成功    db.setTransactionSuccessful();} finally{    //关闭事务    //如果此时已经设置事务执行成功,则sql语句生效,否则不生效    db.endTransaction();}
Display data from the database to the screen
    1. Arbitrarily inserting some data
    2. Define Business Bean:Person.java
    3. Read all data from a database

      Cursor cs = db.query("person", null, null, null, null, null, null);while(cs.moveToNext()){    String name = cs.getString(cs.getColumnIndex("name"));    String phone = cs.getString(cs.getColumnIndex("phone"));    String money = cs.getString(cs.getColumnIndex("money"));    //把读到的数据封装至Person对象    Person p = new Person(name, phone, money);    //把person对象保存至集合中    people.add(p);}
    4. Display the data in the collection to the screen

       LinearLayout ll = (LinearLayout) findViewById(R.id.ll); for(Person p : people){     //创建TextView,每条数据用一个文本框显示     TextView tv = new TextView(this);     tv.setText(p.toString());     //把文本框设置为ll的子节点     ll.addView(tv); }
    5. Paging Query

      Cursor cs = db.query("person", null, null, null, null, null, null, "0, 10");
Listview
    • Is the one that shows the entries for a row.
    • MVC structure
      • M:model model layer, the data to be displayed ———— people collection
      • V:view view layer, the user sees the interface ———— ListView
      • C:control control layer, manipulating how data is displayed ———— adapter object
    • Each entry is a View object
Baseadapter
    • Two methods that must be implemented

      • First one

        //系统调用此方法,用来获知模型层有多少条数据@Overridepublic int getCount() {    return people.size();}
      • A second

        //系统调用此方法,获取要显示至ListView的View对象//position:是return的View对象所对应的数据在集合中的位置@Overridepublic View getView(int position, View convertView, ViewGroup parent) {    System.out.println("getView方法调用" + position);    TextView tv = new TextView(MainActivity.this);    //拿到集合中的元素    Person p = people.get(position);    tv.setText(p.toString());    //把TextView的对象返回出去,它会变成ListView的条目    return tv;}
    • How many entries can be displayed on the screen, how many times the GetView method will be called, and when the screen is sliding down, GetView will continue to be called, creating more View objects to display to the screen
Cache of Entries
    • When the entry is a screen, the system will cache the entry into memory, when the entry again into the screen, the system will re-call GetView when the cache entry as the Convertview parameter, but the incoming entry is not necessarily the previously cached entry, That is, it is possible for the system to pass the cache of any entry when it calls the GetView method to get the first entry

Data storage and interface presentation based on Android application development (III.)

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.