Android Study Notes (2)

Source: Internet
Author: User
Tags xml parser

Handler usage

1. the Handler class is android. A class in OS, handler. post (Runnable r) can add a thread to the Message Queue; handler. postDelay (Runnable r, long delayTime) adds the thread to the Message Queue after the delay of delayTime milliseconds; handler. removeCalbacks (Runnable r) removes the pending Runnable from the queue.

2. Handler. obtainMessage () can get a message. The message has two Integer Parameters, arg1 and arg2, which can be used to transmit messages. When creating a Handler

Handler handler = new Handler (){

@ Override

Public void handleMessage (Message msg ){

......

}

}

The handler can retrieve messages from the MessageQueue and process them in the handleMessage method. In another place, handler. sendMessage (Message msg) can also be used to send messages to the Message queue.

Handler does not enable another thread for thread processing, but calls another Runnable run function based on the original thread. The HanlderThread class implements the logoff function to process message queues. This class is provided by the Android operating system. Using this class, you can use getLooper () (before using the getLooper () method, you must call the start () method of this class; otherwise, this Looper is null) method to obtain this Looper. Then, the logoff is passed to the Handler constructor as a parameter. At this time, the handleMessage () method of the Handler can be processed by another thread, and the Activity will not be blocked.

Bundle can be considered as a special Map, but its key is fixed to the String type, and there are only several basic data types of values.

When using Message to transmit data, you can use Message. obj to transmit a data before sending the data. This data is an Object. You can also use Message. obj to obtain the Message when processing the Message. In this case, you need to perform a downward transformation. To transmit a large amount of data, you can use Message. setData (Bundle data ).

Message. sendToTarget (); The method can be used to send the message to the Handler that creates the Message, and receive the Message in the Handler.

Use of SQLite

1. Use of SQLiteOpenHelper class

The public abstract class SQLiteOpenHelper class has several functions:

OnCreate (SQLiteDatabase db); this method is called when the database is created for the first time.

OnOpen (SQLiteDatabase db); this method is called when the database is opened

OnUpgrade (SQLiteDatabase db); this method is called when the database needs to be upgraded

GetReadableDatabase (); get the database that can be read

GetWritbaleDatabase (); obtain the database that can be written

We generally inherit this class and then call the constructor (the parent class does not have a default constructor ). The database version is an integer. Starting from 1, this value increases progressively each time the database version is upgraded. When this value changes, it means that the database version has been upgraded.

Use sqlitedatabase.exe cSQL (String SQL) to execute SQL statements.

2. Use of the adb Tool

You can use the adb tool (enter adb in cmd. Before that, you need to configure the environment variable for it. Under sdk/platform-tools, the other is to ensure that the simulator AVD is enabled, otherwise, an error is reported.) To view changes in the database:

Adb shell: Enter the Linux Command Line (the android operating system is Linux-centered)

Ls-l: displays files and folders in the complete Form

Cd data: enter data

Cd data: enter data again

There are many folders (named after the package name of the Application). Each application has a folder.

Cd com. example. sqlite3: enter our current application

After the database is created, there will be a folder named databases.

Cd databases: enter this folder. The created database is displayed.

Sqlite3 mydb: Use SQLite to open mydb

Then you can use the database like Mysql:

Select * from table_name ;......

3. insert data

Use the ContentValues class to help insert data:

ContentValues values = new ContentValues ();

Values. put ("id", 1); // The first parameter is the column name, and the second parameter is the column value.

Values. put ("name", "alvis ");

// The DatabaseHelper class inherits from the SQLiteOpenHelper class

DatabaseHelper dbHelper = new DatabaseHelper (MainActivity. this, "mydb ");

// Obtain a database object

SQLiteDatabase db = dbHelper. getWritableDatabase ();

Db. insert ("user", null, values); // call the insert method to insert data.

The first parameter of the insert method is the table name, and the second parameter is null. The third is the ContentValues object with data.

4. Update Data

DatabaseHelper dbHelper = new DatabaseHelper (MainActivity. this, "mydb ");

// Obtain a database object

SQLiteDatabase db = dbHelper. getWritableDatabase ();

ContentValues values = new ContentValues ();

Values. put ("name", "alvis ");

Db. update ("user", values, "id = ?", New String [] {"1"}); // use placeholders to set parameters

The entire sentence actually forms a sentence:

Update user set name = 'alvis 'where id = 1;

The first parameter of the update method is the name of the table to be updated, the second parameter is the ContentValues object with the value to be updated, and the third parameter is the condition of the where clause (there may be multiple ), the fourth parameter is the value of the where clause. The type is String [].

5. query data

DatabaseHelper dbHelper = new DatabaseHelper (MainActivity. this, "mydb ");

SQLiteDatabase db = dbHelper. getWritableDatabase ();

Cursor cursor = db. query ("user", new String [] {"id", "name"}, "id = ?", New String [] {"1"}, null, null, "id ");

While (cursor. moveToNext ()){

// Process the obtained data here

String result = cursor. getString (cursor. getColumnIndex ("name "));

System. out. println (result );

}

Cursor. the moveToNext () method has two functions: move the cursor down to check whether there is a record, and true is returned if there is one; otherwise, false is returned, that is, when the pointer is moved to the next position, it also determines whether there is a value.

The parameters of the query method are in sequence (the following three parameters are strings ):

Table Name, queried field, query condition, condition parameter, groupBy, having, orderBy

In fact, a select statement is decomposed into many parts.

When Using cursor to retrieve data, the parameter must be used to query the index of the column where the data is located. This index can be obtained through cursor. getColumn (String columnName), so the preceding method is used.

We recommend that you do not rely too much on the database or store too much data in the SQLite database, because many strange problems may occur during development.

Android program debugging

You can use the Log class to output debugging information:

Log. I (String tag, String message); // Info-level

Log. v (String tag, String message); // fatal

Log. w (String tag, String message); // warning

Log. e (String tag, String message); // Error

Log. d (String tag, String message); // debug

File Download

1. Steps for downloading an object:

1) create a URL object

URL url = new URL (String urlStr );

2) create an HttpURLConnection

HttpURLConnection urlConn = (HttpURLConnection) url. openConnection ();

3). Obtain an InputStream object

InputStream inputStream = urlConn. getInputStream ();

Then you can use stream operations to read this inputStream.

4). Access to the network: declare in Manifest. xml:

<Uses-permission android: name = "android. permission. INTERNET"/>

Source code:

Class DownloadMP3Listener implements OnClickListener {

@ Override

Public void onClick (View v ){

HttpDownloader httpDownloader = new HttpDownloader ();

Int status = httpDownloader. downFile ("http: // 192.168.2.104: 8080/source/yiwangeshebudemo-"," Download "," 10 thousand not allowed ");

}

}

Error: android. OS. NetworkOnMainThreadException

This exception probably means an exception occurs when the main thread accesses the network. Android versions earlier than Android 4.0 support network access in the main thread, but later than Android 4.0 optimized this part of the program. That is to say, the code for network access cannot be written in the main thread.

Solution: restart a thread to run network-related code.

Class DownloadMP3Listener implements OnClickListener {

@ Override

Public void onClick (View v ){

New Thread () {// re-enable a Thread to access the network

@ Override

Public void run (){

HttpDownloader httpDownloader = new HttpDownloader ();

Int status = httpDownloader. downFile ("http: // 192.168.2.104: 8080/source/yiwangeshebudemo-"," Download "," 10 thousand not allowed ");

}

}. Start ();

}

}

2. Access the SD card

1). Get the directory of the SD card of the current device: Usually/SDCARD

String path = Environment. getExternalStorageDirectory ();

2). Set the permission to access the SD card in the Manifest. xml file (the same as the application tag)

<Uses-permission android: name = "android. permission. INTERNET"/>

ContentProvider preliminary

1. Each ContentProvider has a public URI, which indicates the data provided by this ContentProvider. The ContentProvider provided by Android is in the android. provider package.

2. functions provided by ContentProvider:

Query (): query insert (): insert update (): update

Delete (): delete getType (): Get Data Type onCreate (): callback function at creation

3. Implement the ContentProvider process:

1) define a CONTENT_URI constant

2) define a class that inherits the ContentProvider class

3) Implement the query, insert, update, delete, getType, and onCreate methods.

4) declare in AndroidManifest. xml

XML File Parsing

ContentHandler Interface

ContentHandler is a special SAX interface in a Java class package, which is located at org. xml. in the sax package, this interface encapsulates some methods for event processing. When the XML Parser starts to parse the XML input file, it will encounter some special events, such as the beginning and end of a document, the beginning and end of an element, and the character data in an element. When these events occur, the XML Parser calls the corresponding method in the ContentHandler interface to respond to the event.

The ContentHandler interface has the following methods:

Void startDocument ()

Void endDocument ()

Void startElement (String uri, String localName, String qName, Attributes atts)

Void endElement (String uri, String localName, String qName)

Void characters (char [] ch, int start, int length) Call

The general process is as follows:

1). Create an event handler

2) create a SAX Parser

3) Allocate the event handler to the parser

4) parse the document and send it to the handler every time

Example:

// 1. Create a SAXParserFactory

SAXParserFactory factory = SAXParserFactory. newInstance ();

// 2. Use this factory to obtain an XMLReader

XMLReader reader = factory. newSAXParser (). getXMLReader ();

// 3. Set the content processor for XMLReader

// Note that the parameter of this method is ContentHander.

// There are too many methods, so the adapter mode is used here. MyContentHandler inherits from DefaultHandler

//, While DefaultHandler implements the ContentHanlder interface.

Reader. setContentHandler (new MyContentHandler ());

// 4. Start File Parsing

Reader. parse (new InputSource (new StringReader (xml )));

Broadcast Mechanism

To listen to a type of event, you must declare it in the Manifest. xml file:

<Cycler android: name = ". TestReceiver">

<Inteng-filter>

<Action androi: name = "andriod. intent. action. EDIT"/>

</Intent-filter>

</Cycler>

At the same time, the receiver must inherit the BroadcastReceiver class and rewrite the onReceiver method:

Class TestReceiver extends BroadcastReceiver {

@ Override

Public void onReceiver (Context context, Intent intent ){

// Write the processing process here

}

}

Pay attention to the matching of the blue part.

The sender can use:

Intent intent = new Intent ();

Intent. setAction (Intent. ACTION_EDIT );

TestActivity. this. sendBrodcast (intent );

Note that the red part must be matched; otherwise, the message cannot be received.

The general process of this program is: TestActivity broadcasts an intent whose action is ACTION_EDIT. TestReceiver is a broadcast receiver because it inherits BroadcastReceiver, however, intent that does not receive the broadcast from TestActivity must be viewed in Manifest. testReceiver is configured in the xml file.

In Manifest. in the configuration of TestReceiver in the xml file, the <action> tag of <intent-filter> specifies the action that TestReceiver listens, only when the action in the intent broadcast by TestActivity is the same as the action here will it receive it. At this time, a TestReceiver will be generated and the onReceiver method of this class will be called.

Note: TestReceiver only processes the object once. If it has been processed, the object will be useless. If the same broadcast is sent, the operating system will generate another object for processing.

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