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
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
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
Display data from the database to the screen
- Arbitrarily inserting some data
- Define Business Bean:Person.java
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);}
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); }
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
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.)