Layout, SD path, unit test, SQLITEPC egg source Rental and ListView

Source: Internet
Author: User
Tags sqlite create database

Relative PC egg Source Rental dsluntan.com q:3393756370 vx:17061863513 layout relativelayout
Component default left-aligned, top-aligned
Sets the component to the right of the specified component
android:layout_torightof= "@id/TV1"

Sets the bottom of the specified component
android:layout_below= "@id/TV1"

Set the right-justified parent element
Android:layout_alignparentright= "true"

Sets the right alignment to the specified component
android:layout_alignright= "@id/TV1"

Linear layout LinearLayout
Specify the arrangement direction of each node

Set Right alignment
Android:layout_gravity= "Right"

When vertical layout, only left and right align and center horizontally, top bottom alignment Vertical Center invalid

When horizontal layout, only top bottom is aligned and centered vertically
When using match_parent, be careful not to put the other components out
A very important attribute of linear layout: weights
android:layout_weight= "1"
Weight: Distributes the remaining width or height of the screen proportionally
Frame Layout Framelayout
The default components are left-aligned and top-aligned, with each component equivalent to a div
You can set the upper and lower left and right alignment, horizontal vertical center, the same way as the linear layout
android:layout_gravity= "Bottom"

cannot be compared to other component layouts

Table Layout Tablelayout
Each node is a row, and each of its child nodes is a column
The nodes in the table layout can not be set to a wide height because the settings are also invalid

The child node width of the root node matches the parent element, and the content of the package is high
The node's child node width is the parcel content, the content of the parcel is high
The above default properties cannot be modified
The following properties can be set in the root node, which means that the 1th column stretches to fill the remaining space of the screen width
android:stretchcolumns= "1"

Absolute layout absolutelayout
directly specifies the x, y coordinates of the component
android:layout_x= "144DP"
Android:layout_y= "154DP"
Note: The direct copy of the project needs to be changed: project name, application package name, r file re-guide package

Path API Description
Getfilesdir () The path to the resulting file object is the data/data/app package name/files
Files stored in this path, as long as you do not delete, it has been in
Getcachedir () The path to the resulting file object is the Data/data app package name/cache

Files stored under this path may be deleted when memory is low
The System Management application interface clears the cache, clears the contents of the cache folder, clears the data, and clears the entire package.

Path to SD card
2.2 Before the SD card path: SDcard
4.3 Before the SD card path: Mnt/sdcard
4.3 Start, SD card path: Storage/sdcard

The simplest way to open an SD card
File File = new file ("Sdcard/test.txt");

Use API to get the real path of SD card, some phone brands will change the path of SD card
Environment.getexternalstoragedirectory ()

Determine if the SD card is ready
if (Environment.getexternalstoragestate (). Equals (environment.media_mounted))

Get SD capacity
Import Java.io.File;

Import android.app.Activity;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.os.StatFs;
Import Android.text.format.Formatter;
Import Android.widget.TextView;

Public class Mainactivity extends Activity {
Private TextView tv;br/> @Override
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
TV = (TextView) Findviewbyid (r.id.tv);
if (Existsdcard ()) {
String available = Formatsize (getavailable ());
String allsize = this.formatsize (Getallsize ());
Tv.settext ("Total Space:" +allsize+ "free Space" +available);
}
}

 //Get usable capacity private long getavailable () {File path = Environment.getexternalstoragedirectory ();    StatFs SF = new StatFs (Path.getpath ());    Gets the size of a single data block (Byte) long blockSize = Sf.getblocksizelong ();    Gets the number of all data blocks long availbleblocks = Sf.getavailableblockslong (); return blocksize* Availbleblocks;}    Get total capacity private long getallsize () {File path = Environment.getexternalstoragedirectory ();    StatFs SF = new StatFs (Path.getpath ());    Gets the size of a single data block (Byte) long blockSize = Sf.getblocksizelong ();    Gets the number of all data blocks long allblocks = Sf.getblockcountlong (); return blocksize*allblocks;} Format Function Private String formatsize (long size) {return formatter.formatfilesize (this, size);} Whether to mount the SD card private Boolean Existsdcard () {if (Environment.getexternalstoragestate (). Equals (Environment.media    _mounted)) {return true; } else return false;}  

}
Note: When using APIs such as Getblockcountlong (), the main SDK version, SDK17 is not supported Getblockcountlong (), the lower version of the SDK still uses Getblockcount () and so on without a long
Write a picture description here

Test
Test classification
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 (e.g. Monkey 1000: Random click on the screen 1000 times)
Stress test: Pressure test
Unit Tests in Android
You first use a class to inherit from Androidtestcast:

Import Android.test.AndroidTestCase;

public class Test extends Androidtestcase {
public void Test () {
The code or method of the TODO test
}
}
and make the following configuration in:

<instrumentation android:name= "Android.test.InstrumentationTestRunner" android:allowbackup= "true"
android:icon= "@drawable/ic_launcher"
Br/>android:targetpackage= "app package name to test" >
Android:allowbackup= "true"
android:icon= "@drawable/ic_launcher"
Android:theme= "@style/apptheme" >

SQLite Lightweight relational database creates a database that needs to be used when the Api:sqliteopenhelper database is created: The OnCreate method is called when the database is upgraded: Onupgrade method Import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqliteopenhelper;public class Myopenhelper extends Sqliteopenhelper {public MyOpenHelper ( Context context) {//Parameter description: Contextual, database name, cursor factory (default null), version (for upgrade) Super (context, "test.db", NULL, 1);} @Overridepublic void OnCreate (Sqlitedatabase db) {//CREATE TABLE Db.execsql ("CREATE TABLE person (_id integer PRIMARY key Autoincre ment, name Char (TEN), Phone char (), salary Integer (10)) "); When the database is upgraded, call @overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {System.out.println (" Database upgrade ... ");} Create Database//Create Openhelper object Myopenhelper Oh = new Myopenhelper (GetContext (), "test.db", NULL, 1);//Get Database object, if database does not exist, create database First, Sqlitedatabase db = Oh.getwritabledatabase (); Getwritabledatabase (): Open a writable database Getreadabledatabase () : Open a read-only database when disk space is insufficient, otherwise open can read and write database database additions and deletions to change the database can use the SQL statement, and then Db.execsql ("SQL statement") can be completed! NoteMeaning: Setup primarily implements pre-test initialization, while teardown mainly implements garbage collection after the test is completed. @Overrideprotected void SetUp () throws Exception {Super.setup ();//Get Virtual Context Object Oh = new Myopenhelper (GetContext (), "test.db ", null, 1);} @Overrideprotected void TearDown () throws Exception {Super.teardown ();//Close Database Db.close ();} Use API to implement additions/deletions//Use cursors to access each data individually, public void Select () {cursor cursor = db.rawquery ("SELECT * from table name", null);//Move the pointer to the next row while (c Ursor.movetonext ()) {//First gets the column index by column name, and then gets the contents of the column String str = cursor.getstring (cursor.getcolumnindex ("field name 1")); String str2 = cursor.getstring (Cursor.getcolumnindex ("Field Name 2")); int STR3 = Cursor.getint (Cursor.getcolumnindex ("Field Name 3")); System.out.println (STR+STR2+STR3); }}public void Insertapi () {contentvalues values = new Contentvalues (), Values.put ("Field 1", "value"), Values.put ("Field 2", "Val UE "); Values.put ("Field 3", "value"); return value-1, insert failed long L = db.insert ("table name", null, values);} public void Deleteapi () {///Because the object to be passed in is an array of int i = db.delete ("Table name", "_id =?", New string[]{"4"}); public void Updateapi () {ContentvalUEs values = new Contentvalues (); Values.put ("Field name", "value"); int i = db.update ("table name", values, "_id =?", New string[]{"1"}); Transactions guarantee that multiple SQL statements either succeed at the same time, or fail at the same time, and the failure will happen! public void Transaction () {try{//Open transaction db.begintransaction ();//todo Modify table Data ...//SET transaction execution succeeds, rollback if this line of code is not executed at commit Db.settransactionsuccessful (); } catch (Exception e) {//The exception here must be captured E.printstacktrace ();} finally{//Close transaction, commit data Db.endtransaction ();}} The ListView is used to display the list of MVC structures M:model The model layer, the data to be displayed ———— people collection v:view The view layer, the interface the user sees ———— the Listviewc:control control layer, how the data is displayed ———— Adapter object Each entry is a View object Baseadapter must implement two methods//Adapter class class Myadapter extends Baseadapter {//System call: Gets the number of model layer data @Override public int GetCount () {return list.size ();//System call: Gets the View object to display to the ListView//Convertview: Entries cached before the system @Override public View GetView (int position, View Convertview, ViewGroup parent) {people p = list.get (position); View view = null; if (Convertview = = null) {//Fill the layout file as a View object (see source, this is three ways)//Layoutinflater Layin = Layoutinflater.from (mainactivity.this ); Layoutinflater Layin = (layoutinflater) getsystemservice ("Layout_inflater"); View = Layin.inflate (R.layout.item_listview,null); View = View.inflate (Getapplicationcontext (), r.layout.item_listview, NULL); } else {view = Convertview; TextView tv_name = (TextView) View.findviewbyid (r.id.tv_name); TextView Tv_phone = (TextView) View.findviewbyid (R.id.tv_phone); TextView Tv_sa = (TextView) View.findviewbyid (R.ID.TV_SA); Tv_name.settext (P.getname ()); Tv_phone.settext (P.getphone ()); Tv_sa.settext (P.getsalary ()); } return view; }} How many entries can be displayed on the screen, how many times the GetView method will be called, and when the screen is down, GetView will continue to be called, creating more View objects to display to the cache of the screen entries when the entry is out of the screen, the system will cache the entry to memory, and when the entry goes to the screen again, The system will pass the cached entry as the Convertview parameter when the GetView is called, but the incoming entry is not necessarily the one previously cached, 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! Arrayadapter displays a string in the entry string[] objects = new string[]{"AAA", "BBB", "CCC"}; ListView LV = (ListView) Findviewbyid (r.id.lv);//ARG1: Specifies the layout file to populate//ARG2: Specifies which text box the text is displayed in Lv.setadapter (new Arrayadapter (This, R.layout.item_array, R.id.tv_name, objects)); Simpleadapter can display a variety of data in an entry encapsulated in the list, each element of the collection holds the data that an entry displays, because there may be multiple data, and the generic of the collection can only specify one type of data, so the data is stored in the map first. The map is placed in list protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); LV = (ListView) Findviewbyid (r.id.lv); Encapsulate all the data that each item needs to process into a map, and then encapsulate the map in the list//to ensure that each element of the list contains all the data needed for an entry list > data = new ArrayList > (); Map m1 = new HashMap (); M1.put ("Name", "AAA"); M1.put ("Photo", R.drawable.a) ; Data.add (M1); Map m2 = new HashMap (), M2.put ("name", "BBB"), M2.put ("Photo", R.dra WABLE.B); Data.add (m2); Map m3 = new HashMap (); M3.put ("Name", "CCC"); M3.put ("Phot O ", r.drawable.c); Data.add (m3); Lv.setadapter (New Simpleadapter (Mainactivity.this, data, R.layout.item_listview, new string[]{"name", "Photo"}, New Int[]{r.id.name, R.ID.IV}));

Layout, SD path, unit test, SQLITEPC egg source Rental and listview

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.