Android Basics Summary (iii)

Source: Internet
Author: User
Tags sqlite database

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.itheima.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
dialog box OK Cancel dialog box
    • Create a Dialog builder object similar to Factory mode
    • AlertDialog.Builder builder = new Builder(this);
    • Set the title and body
    • builder.setTitle("警告");builder.setMessage("若练此功,必先自宫");
    • Set OK and Cancel buttons

      builder.setPositiveButton("现在自宫", new OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        // TODO Auto-generated method stub        Toast.makeText(MainActivity.this, "恭喜你自宫成功,现在程序退出", 0).show();    }});builder.setNegativeButton("下次再说", new OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        // TODO Auto-generated method stub        Toast.makeText(MainActivity.this, "若不自宫,一定不成功", 0).show();    }});
    • Using the Builder to create a dialog box object

      AlertDialog ad = builder.create();ad.show();
Single-selection dialog box
    AlertDialog.Builder builder = new Builder(this);    builder.setTitle("选择你的性别");
    • Define a radio option
    • final String[] items = new String[]{        "男", "女", "其他"};//-1表示没有默认选择//点击侦听的导包要注意别导错builder.setSingleChoiceItems(items, -1, new OnClickListener() {    //which表示点击的是哪一个选项    @Override    public void onClick(DialogInterface dialog, int which) {        Toast.makeText(MainActivity.this, "您选择了" + items[which], 0).show();        //对话框消失        dialog.dismiss();    }});builder.show();
Multi-Select dialog box
    AlertDialog.Builder builder = new Builder(this);    builder.setTitle("请选择你认为最帅的人");
    • The option to define multiple selections, because you can select multiple, so you need a Boolean array to record which options are selected
    • final String[] items = new String[]{        "赵帅哥",        "赵师哥",        "赵老师",        "侃哥"};//true表示对应位置的选项被选了final boolean[] checkedItems = new boolean[]{        true,        false,        false,        false,};builder.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener() {    //点击某个选项,如果该选项之前没被选择,那么此时isChecked的值为true    @Override    public void onClick(DialogInterface dialog, int which, boolean isChecked) {        checkedItems[which] = isChecked;    }});builder.setPositiveButton("确定", new OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        StringBuffer sb = new StringBuffer();        for(int i = 0;i < items.length; i++){            sb.append(checkedItems[i] ? items[i] + " " : "");        }        Toast.makeText(MainActivity.this, sb.toString(), 0).show();    }});builder.show();

Android Basics Summary (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.