19 Dec
Posted by support as General 1,428 views, 0 Comments
A TimePicker is a Widget that allows the User to Select the time by hour, minute and AM or PM.
Start a new project / Activity called HelloTimePicker.
Modify HelloTimePicker.java code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package com.example.test; import java.util.Calendar; import android.app.Activity; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.TimePicker; public class HelloTimePicker extends Activity (private TextView mTimeDisplay; private Button mPickTime; private int mHour; private int mMinute; static final int TIME_DIALOG_ID = 0; @ Overrideprotected void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.main); / / capture our View elements mTimeDisplay = (TextView) findViewById (R.id.timeDisplay); mPickTime = (Button) findViewById (R.id.pickTime); / / add a click listener to the button mPickTime.setOnClickListener (new View.OnClickListener () (public void onClick (View v) (showDialog (TIME_DIALOG_ID); ))); / / get the current time final Calendar c = Calendar.getInstance (); mHour = c.get (Calendar.HOUR_OF_DAY); mMinute = c.get (Calendar.MINUTE); / / display the current date updateDisplay (); } Overrideprotected Dialog onCreateDialog (int id) (switch (id) (case TIME_DIALOG_ID: return new TimePickerDialog (this, mTimeSetListener, mHour, mMinute, false); ) return null; ) / / updates the time we display in the TextViewprivate void updateDisplay () (mTimeDisplay.setText ( new StringBuilder (). append (pad (mHour)). append (":"). append (pad (mMinute ))); } private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener () (public void onTimeSet (TimePicker view, int hourOfDay, int minute) (mHour = hourOfDay; mMinute = minute; updateDisplay (); )); private static String pad (int c) (if (c> = 10) return String.valueOf (c); else return "0 "+ String.valueOf (c); )) |
Layout-> main.xml
1 | <? xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: orientation = "vertical"> <TextView android:id="@+id/timeDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=""/> <Button android : id = "@ + id / pickTime" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Change the time "/></ LinearLayout> |
Run Now run it. Run the results are as follows:

Source Download: HelloTimePicker.zip
18 Dec
Posted by support as General 369 views, 0 Comments
A WebView allows you to Create your own Web Browser Activity. In this Tutorial, we'll Create a simple Activity that can View Web pages.
Learning Address: http://androidappdocs.appspot.com/guide/tutorials/views/hello-webview.html
HelloWebView.java Code
1 | package com.example.test; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class HelloWebView extends Activity (WebView webview; / ** Called when the activity is first created. * / @ Override public void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.main); webview = (WebView) findViewById (R.id.webview); webview.getSettings (). setJavaScriptEnabled (true) ; webview.loadUrl (http://ditu.google.cn);)) |
Layout-> main.xml
1 | <? xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: orientation = "vertical"> <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </ LinearLayout> |
Implementation of the Eclipse-> HelloWebViewAndroid-> Android Application Show pictures are as follows:

Code download HelloWebView.zip
18 Dec
Posted by support as General 668 views, 0 Comments
A RelativeLayout is a ViewGroup that allows you to layout child elements in positions relative to the parent or siblings elements.
1 | <? xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Type here:"/> <EditText android: id = " @ + id / entry "android: layout_width =" fill_parent "android: layout_height =" wrap_content "android: background =" @ android: drawable / editbox_background "android: layout_below =" @ id / label "/> <Button android: id = "@ + id / ok" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_below = "@ id / entry" android: layout_alignParentRight = "true" android: layout_marginLeft = "10dip" android: text = " OK "/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@id/ok" android:layout_alignTop="@id/ok" android:text="Cancel" /> < / RelativeLayout> |
Pay attention to each of the additional layout_* attributes (besides the usual width and height, which are required for all elements). When using relative layout, we use attributes like layout_below and layout_toLeftOf to describe How we'd like to position each View. Naturally, these are different relative positions, and the value of the attribute is the id of the element we want the position relative to.
onCreate() method:
1 | public void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.main);) |
R.layout.main refers to the main.xml layout file.
HelloSpinner.java Source
1 | package com.example.test; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Spinner; public class HelloSpinner extends Activity (@ Overridepublic void onCreate (Bundle savedInstanceState) ( super.onCreate (savedInstanceState); setContentView (R.layout.main); Spinner s = (Spinner) findViewById (R.id.spinner); ArrayAdapter adapter = ArrayAdapter.createFromResource (this, R.array.planets, android.R. layout.simple_spinner_item); adapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item); s.setAdapter (adapter);)) |
layout-> main.xml
1 | <? xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: orientation = "vertical" android: padding = "10dip" android: layout_width = "fill_parent" android: layout_height = "wrap_content"> <TextView android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_marginTop = "10dip" android: text = "Please select a planet: "/> <Spinner android: id =" @ + id / spinner "android: layout_width =" fill_parent "android: layout_height =" wrap_content "android: drawSelectorOnTop =" true "android: prompt =" @ string / planet_prompt "/ > </ LinearLayout> |
values-> arrays.xml
1 | <resources> <string-array name="planets"> <item> Mercury </ item> <item> Venus </ item> <item> Earth </ item> <item> Mars </ item> <item> Jupiter < / item> <item> Saturn </ item> <item> Uranus </ item> <item> Neptune </ item> </ string-array> </ resources> |
value-> strings.xml
1 | <? xml version = "1.0" encoding = "utf-8"?> <resources> <string name="hello"> Hello World, HelloSpinner! </ string> <string name="app_name"> HelloSpinner </ string> <string name="planet_prompt"> Choose a planet </ string> </ resources> |
run it 
In the development for the control to add Listener is a very common work, the easiest way to add Listener can be:
1 | findViewById (R.id.myButton). setOnClickListener (new View.OnClickListener () (public void onClick (View v) (/ / Do stuff))); |
Add a Listener using the above method has a drawback is that if control is too large, Listener will increase the number, so the following tips can be used to reduce the number of Listener:
1 | View.OnClickListener handler = View.OnClickListener () (public void onClick (View v) (switch (v.getId ()) (case R.id.Button01: / / doStuff break; case R.id.Button02: / / doStuff break;))) findViewById (R.id.myButton). setOnClickListener (handler); findViewById (R.id.myOtherButton). setOnClickListener (handler); |
The Android1.6 inside, add the Listener's work has become fairly simple (feeling more like doing web programming!), Concrete steps are as follows:
1. First, the definition in the layout inside the Button and specify the response Listener
1 | <? xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: orientation = "vertical" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android: text = "Button01" android : id = "@ + id/Button01" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: onClick = "myClickHandler01" /> <Button android: text = "Button02" android: id = "@ + id / Button02 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: onClick =" myClickHandler02 "/> <TextView android: layout_width =" fill_parent "android: layout_height =" wrap_content "android: text =" @ string / hello "/> </ LinearLayout> |
These two lines of which the following are new features:
android: onClick = "myClickHandler01"
android: onClick = "myClickHandler02"
2. In the event inside the definition of public methods myClickHandler01, and myClickHandler02 (Note that these two methods must have a View of the shape parameter).
1 | package com.ray.test; import android.app.Activity; import android.os.Bundle; import android.view.View; public class TestOnClickListener extends Activity (@ Override public void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState) ; setContentView (R.layout.main);) public void myClickHandler01 (View target) (setTitle ( "myClickHandler01");) public void myClickHandler02 (View target) (setTitle ( "myClickHandler02");)) |
Of course, you can also use this wording:
The two buttons set to the same Listener
android: onClick = "myClickHandler"
android: onClick = "myClickHandler"
1 | package com.ray.test; import android.app.Activity; import android.os.Bundle; import android.view.View; public class TestOnClickListener extends Activity (@ Override public void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState) ; setContentView (R.layout.main);) public void myClickHandler (View target) (switch (target.getId ()) (case R.id.Button01: setTitle ( "myClickHandler01"); break; case R.id.Button02 : setTitle ( "myClickHandler02"); break;))) |
Refer to the article: "UI framework changes in Android 1.6" (take over the wall)
18 Dec
Posted by support as General 949 views, 0 Comments
Learning Address: http://androidappdocs.appspot.com/guide/tutorials/views/hello-mapview.html
HelloItemizedOverlay.java Code
1 | package com.example.test; import java.util.ArrayList; import android.graphics.drawable.Drawable; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.OverlayItem; public class HelloItemizedOverlay extends ItemizedOverlay (private ArrayList <OverlayItem> mOverlays = new ArrayList <OverlayItem> (); public HelloItemizedOverlay (Drawable defaultMarker) (super (boundCenterBottom (defaultMarker ));// TODO Auto-generated constructor stub) @ Overridepublic int size () (return mOverlays. size ();) public void addOverlay (OverlayItem overlay) (mOverlays.add (overlay); populate ();}Overrideprotected OverlayItem createItem (int i) (return mOverlays.get (i);)) |
HelloMapView1.java Code
1 | package com.example.test; import java.util.List; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.ZoomControls; import com.google.android . maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; public class HelloMapView1 extends MapActivity (LinearLayout linearLayout; MapView mapView; ZoomControls mZoom; List <Overlay> mapOverlays; Drawable drawable; HelloItemizedOverlay itemizedOverlay; / ** Called when the activity is first created. * / @ Override public void onCreate (Bundle savedInstanceState) (super . onCreate (savedInstanceState); setContentView (R.layout.main); mapView = (MapView) findViewById (R.id.mapview); mapView.setBuiltInZoomControls (true); mapOverlays = mapView.getOverlays (); drawable = this.getResources ( ). getDrawable (R.drawable.androidmarker); itemizedOverlay = new HelloItemizedOverlay (drawable); GeoPoint point = new GeoPoint (19240000, -99120000); OverlayItem overlayitem = new OverlayItem (point, "", ""); itemizedOverlay.addOverlay ( overlayitem); mapOverlays.add (itemizedOverlay);) @ Override protected boolean isRouteDisplayed () (return false;)) |
Layout-> mail.xml
1 | <? xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: id = "@ + id / mainlayout "android: orientation =" vertical "android: layout_width =" fill_parent "android: layout_height =" fill_parent "> <com.google.android.maps.MapView android: id =" @ + id / mapview "android: layout_width =" fill_parent "android: layout_height =" fill_parent "android: clickable =" true "android: apiKey =" Your Maps API Key "/> <LinearLayout android: id =" @ + id / zoomview "android: layout_width =" wrap_content "android: layout_height = "wrap_content" android: layout_alignBottom = "@ id / mapview" android: layout_centerHorizontal = "true "/></ RelativeLayout> |
Implementation of the android Application, found that google maps can not be displayed, please know the cause of the friend told my, thank you.
18 Dec
Posted by support as General 1,091 views, 0 Comments
A TableLayout is a ViewGroup that will Lay child View elements into rows and columns.
1 | <? xml version = "1.0" encoding = "utf-8"?> <TableLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: stretchColumns = "1"> <TableRow> <TextView android:layout_column="1" android:text="Open..." android:padding="3dip" /> <TextView android: text = " Ctrl-O "android: gravity =" right "android: padding =" 3dip "/> </ TableRow> <TableRow> <TextView android: layout_column =" 1 "android: text =" Save ... "android: padding = "3dip" /> <TextView android:text="Ctrl-S" android:gravity="right" android:padding="3dip" /> </ TableRow> <TableRow> <TextView android: layout_column = "1" android: text = "Save As ..." android: padding = "3dip" /> <TextView android:text="Ctrl-Shift-S" android:gravity="right" android:padding="3dip" /> </ TableRow > <View android:layout_height="2dip" android:background="#FF909090" /> <TableRow> <TextView android:text="X" android:padding="3dip" /> <TextView android: text = "Import. .. "android: padding =" 3dip "/> </ TableRow> <TableRow> <TextView android:text="X" android:padding="3dip" /> <TextView android: text =" Export ... "android : padding = "3dip" /> <TextView android:text="Ctrl-E" android:gravity="right" android:padding="3dip" /> </ TableRow> <View android: layout_height = "2dip" android: background = "# FF909090" /> <TableRow> <TextView android:layout_column="1" android:text="Quit" android:padding="3dip" /> </ TableRow> </ TableLayout> |
Notice How this resembles the structure of an HTML Table. TableLayout is like the table element; TableRow is like a tr element; but for our cells like the HTML td element, we can use any kind of View. Here, we use TextView for the cells.
onCreate() method:
1 | public void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.main);) |
R.layout.main refers to the main.xml layout file.
You should see the following:

18 Dec
Posted by support as General 675 views, 0 Comments
Original From: http://blog.sina.com.cn/s/blog_4ca975460100g5yj.html
Android if they had to switch on the screen solution
The time in the development of the game, some games are only horizontal screen play, so when placed in the erection of mobile phone, to keep the game screen is still horizontal screen. To achieve this requirement is very simple to configure in the AndroidManifest.xml inside look on it. Add this line android: screenOrientation = "landscape".
For example, (landscape is a horizontal, portrait vertical):
Java code
<? xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package = "com.ray.linkit"
android: versionCode = "1"
android: versionName = "1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android: name = ". Main"
android: label = "@ string / app_name"
android: screenOrientation = "portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</ intent-filter>
</ activity>
<activity android: name = ". GamePlay"
android: screenOrientation = "portrait"> </ activity>
<activity android: name = ". OptionView"
android: screenOrientation = "portrait"> </ activity>
</ application>
<uses-sdk android:minSdkVersion="3" />
</ manifest>
<? xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package = "com.ray.linkit"
android: versionCode = "1"
android: versionName = "1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android: name = ". Main"
android: label = "@ string / app_name"
android: screenOrientation = "portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</ intent-filter>
</ activity>
<activity android: name = ". GamePlay"
android: screenOrientation = "portrait"> </ activity>
<activity android: name = ". OptionView"
android: screenOrientation = "portrait"> </ activity>
</ application>
<uses-sdk android:minSdkVersion="3" />
</ manifest>
In addition, android dynamic switching each time the screen will restart Activity, so it should be in the Activity prior to their destruction to save the state of current activity in the Activity, when re-Create load configuration, as carried out in the game will not be automatically restarted!
Reprinted from: http://rayleung.javaeye.com/blog/426972
Answers Time :2009-01-18 18:04
When the screen when the screen becomes horizontal, the system will re-calls the current Activity's OnCreate method, you can put on your OnCreate the following methods to check the current in the direction of, then you can let your SetContentView to load a different Layout xml.
if (this.getResources (). getConfiguration (). orientation == Configuration.ORIENTATION_LANDSCAPE) (
Log.i ( "info", "landscape");
)
else if (this.getResources (). getConfiguration (). orientation == Configuration.ORIENTATION_PORTRAIT) (
Log.i ( "info", "portrait");
)
When switching on the screen first need to add the configuration in the androidmanifest.xml
android: configChanges = "orientation | keyboardHidden | navigation
So in the program. Activity will not be repeated call onCreate ()
Does not even call onPause.onResume.
Will call a onConfigurationChanged (Configuration newConfig)
This is the XML configuration option to join the premise.
If you join the options on the premise. As stated above. Activity will be re-activated onCreate method
According to your own needs to choose the configuration changes when the mechanism for handling such a better life.
Custom ContentProvider
———-
The content provider is used to deal with data sources, while the content parser (ContentResolver) responsible for operating the specific content provider. The data source can be a file or database. More content resolver can simultaneously access the content provider because it is thread-safe .
A URI can identify a resource, and a content provider can have multiple URI. But all the same URI of the AUTHORITY.
Android no shared memory, so to access data from another process must be through the content provider to operate the device.
1. Inheritance ContentProvider, and override all abstract methods.
Android OS automatically call ContentProvider of onCreate () method, while the database is on-demand enabled.
2. Configuration AndroidManifest.xml
<provider android: authorities = "tl.android.provider.bookprovider"
android: name = "tl.android.data.TestContentProvider">
</ provider>
name: Specifies ContentProvider subclass the full class path.
authorities: the specified ContentProvider unique identification (recommended: company name. provider. data table + provider)
3. For the content provider defines various constants.
CONTENT_URI
TABLE_NAME
DATABASE_NAME
DATABASE_VERSION
…
4. ContentResolver inserting data record by
5. To obtain the generated database and view
*. db directory databases in the application of generally under.
For example:
/ data / data / tl.android.apps / databases / books.db
Copy Database to C:
adb pull / data / data / tl.android.apps / databases / books.db c:
Will be generated books.db drag sqlite3.exe (in the Android SDK tools directory)
View database tables
. tables
See the specific form
select * from table_name;
Specific reference code:
TestContentProvider.java
1 | package tl.android.data; import java.util.HashMap; import tl.android.data.TestContentProviderMetaData.BookTableMetaData; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentUris; import android.content . ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; public class TestContentProvider extends ContentProvider (public static final String TAG = "amos_tl"; public DatabaseHelper openHelper = null; / / - Create table column names and JavaBean map. public static HashMap <String, String> sBookProjectionMap = null; static (sBookProjectionMap = new HashMap < String, String> (); sBookProjectionMap.put (BookTableMetaData._ID, BookTableMetaData._ID); sBookProjectionMap.put (BookTableMetaData.BOOK_NAME, BookTableMetaData.BOOK_NAME); sBookProjectionMap.put (BookTableMetaData.BOOK_ISBN, BookTableMetaData.BOOK_ISBN); sBookProjectionMap.put ( BookTableMetaData.BOOK_AUTHOR, BookTableMetaData.BOOK_AUTHOR); sBookProjectionMap.put (BookTableMetaData.CREATED_DATE, BookTableMetaData.CREATED_DATE); sBookProjectionMap.put (BookTableMetaData.MODIFIED_DATE, BookTableMetaData.MODIFIED_DATE);) / / - create the best match URI device private static UriMatcher sUriMatcher = null; / / - registered URI request type private static final int INCOMMING_BOOK_COLLECTION_URI_INDICATOR = 1; private static final int INCOMMING_SINGLE_BOOK_URI_INDICATOR = 2; static (sUriMatcher = new UriMatcher (UriMatcher.NO_MATCH); sUriMatcher.addURI (TestContentProviderMetaData.AUTHORITY, "books" , INCOMMING_BOOK_COLLECTION_URI_INDICATOR); sUriMatcher.addURI (TestContentProviderMetaData.AUTHORITY, "books / #", INCOMMING_SINGLE_BOOK_URI_INDICATOR);) @ Overridepublic int delete (Uri uri, String whereClause, String [] whereArgs) (Log.i (TAG, "del"); / / TODO Auto-generated method stubSQLiteDatabase db = openHelper.getWritableDatabase (); int count = 0; switch (sUriMatcher.match (uri)) (case INCOMMING_BOOK_COLLECTION_URI_INDICATOR: count = db.delete (BookTableMetaData.TABLE_NAME, whereClause, whereArgs); break ; case INCOMMING_SINGLE_BOOK_URI_INDICATOR: String rowID = uri.getPathSegments (). get (1); String where = BookTableMetaData._ID + "=" + rowID + (! TextUtils.isEmpty (whereClause)? "AND (" + whereClause + ')' :""); count = db.delete (BookTableMetaData.TABLE_NAME, where, whereArgs); break; default: throw new IllegalArgumentException ( "Unknown URI" + uri);) this.getContext (). getContentResolver (). notifyChange (uri , null); return count;) @ Overridepublic String getType (Uri uri) (switch (sUriMatcher.match (uri)) (case INCOMMING_BOOK_COLLECTION_URI_INDICATOR: return BookTableMetaData.CONTENT_TYPE; case INCOMMING_SINGLE_BOOK_URI_INDICATOR: return BookTableMetaData.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException ( " Unknown URI "+ uri );}}Overridepublic Uri insert (Uri uri, ContentValues values) (/ / TODO Auto-generated method stubLog.i (TAG," insert "); if (sUriMatcher.match (uri)! = INCOMMING_BOOK_COLLECTION_URI_INDICATOR ) (throw new IllegalArgumentException ( "Unknown URI" + uri);) long now = Long.valueOf (System.currentTimeMillis ()); if (values.containsKey (BookTableMetaData.CREATED_DATE) == false) (values.put (BookTableMetaData. CREATED_DATE, now);) if (values.containsKey (BookTableMetaData.MODIFIED_DATE) == false) (values.put (BookTableMetaData.MODIFIED_DATE, now);) if (values.containsKey (BookTableMetaData.BOOK_NAME) == false) (/ / values.put (BookTableMetaData.BOOK_NAME, "null"); throw new SQLException ( "Failed to insert row, because Book Name is needed" + uri);) if (values.containsKey (BookTableMetaData.BOOK_ISBN) == false) (values . put (BookTableMetaData.BOOK_ISBN, "Unknown ISBN");) if (values.containsKey (BookTableMetaData.BOOK_AUTHOR) == false) (values.put (BookTableMetaData.BOOK_AUTHOR, "Unknown author");) SQLiteDatabase db = openHelper.getWritableDatabase (); long rowID = db.insert (BookTableMetaData.TABLE_NAME, BookTableMetaData.BOOK_NAME, values); if (rowID> 0) (Uri insertBookedUri = ContentUris.withAppendedId (BookTableMetaData.CONTENT_URI, rowID); getContext (). getContentResolver (). notifyChange (insertBookedUri, null); return insertBookedUri;) throw new SQLException ( "Failed to insert row into" + uri);) @ Overridepublic boolean onCreate () (/ / TODO Auto-generated method stubLog.i (TAG, "create table "); openHelper = new DatabaseHelper (this.getContext ()); Log.i (TAG, openHelper.toString ()); return true;) @ Overridepublic Cursor query (Uri uri, String [] projection, String selection, String [ ] selectionArgs, String sortOrder) (/ / TODO Auto-generated method stubLog.i (TAG, "query"); Cursor cursor = null; SQLiteQueryBuilder qb = null; qb = new SQLiteQueryBuilder (); switch (sUriMatcher.match (uri) ) (case INCOMMING_BOOK_COLLECTION_URI_INDICATOR: qb.setTables (BookTableMetaData.TABLE_NAME); qb.setProjectionMap (sBookProjectionMap); break; case INCOMMING_SINGLE_BOOK_URI_INDICATOR: qb.setTables (BookTableMetaData.TABLE_NAME); qb.setProjectionMap (sBookProjectionMap); qb.appendWhere (BookTableMetaData._ID + "=" + uri.getPathSegments (). get (1)); break; default: throw new IllegalArgumentException ( "Unknown URI" + uri);) String orderBy = ""; if (TextUtils.isEmpty (sortOrder)) (orderBy = BookTableMetaData.DEFAULT_SORT_ORDER;) else (orderBy = sortOrder;) SQLiteDatabase db = openHelper.getReadableDatabase (); Cursor c = qb.query (db, projection, selection, selectionArgs, null, null, orderBy); int i = c.getCount (); ContentResolver cr = this.getContext (). getContentResolver (); c.setNotificationUri (cr, uri); return c;) @ Overridepublic int update (Uri uri, ContentValues values, String selection, String [] selectionArgs) (/ / TODO Auto-generated method stubLog.i (TAG, "update"); SQLiteDatabase db = openHelper.getWritableDatabase (); int count = 0; switch (sUriMatcher.match (uri)) (case INCOMMING_BOOK_COLLECTION_URI_INDICATOR: count = db.update ( BookTableMetaData.TABLE_NAME, values, selection, selectionArgs); break; case INCOMMING_SINGLE_BOOK_URI_INDICATOR: String rowID = uri.getPathSegments (). get (1); String where = "BookTableMetaData._ID" + "=" + rowID + (! TextUtils.isEmpty (selection)? "AND (" + selection +')':""); count = db.update (BookTableMetaData.TABLE_NAME, values, where, selectionArgs); break; default: throw new IllegalArgumentException ( "Unknown URI" + uri );) getContext (). getContentResolver (). notifyChange (uri, null); return count ;}//-- create tablepublic class DatabaseHelper extends SQLiteOpenHelper (public DatabaseHelper (Context context) (super (context, TestContentProviderMetaData.DATABASE_NAME, null, TestContentProviderMetaData.DATABASE_VERSION);) @ Overridepublic void onCreate (SQLiteDatabase db) (/ / TODO Auto-generated method stubString sql = "CREATE TABLE" + BookTableMetaData.TABLE_NAME + "(" + TestContentProviderMetaData.BookTableMetaData._ID + "INTEGER PRIMARY KEY," + BookTableMetaData.BOOK_NAME + "TEXT," + BookTableMetaData.BOOK_ISBN + "TEXT," + BookTableMetaData.BOOK_AUTHOR + "TEXT," + BookTableMetaData.CREATED_DATE + "INTEGER," + BookTableMetaData.MODIFIED_DATE + "INTEGER" + ");"; Log . i (TAG, db.getPath ()); db.execSQL (sql);) @ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) (/ / TODO Auto-generated method stubLog.i (TAG, "Upgrade database from "+ oldVersion +" to "+ newVersion +", which will destroy old data! "); String sql =" DROP TABLE IF EXISTS "+ BookTableMetaData.TABLE_NAME; db.execSQL (sql); onCreate (db);) )) class TestContentProviderMetaData (public static final String DATABASE_NAME = "books.db"; public static final int DATABASE_VERSION = 1; public static final String AUTHORITY = "tl.android.provider.bookprovider"; public static final String BOOKS_TABLE_NAME = "books" ; public static final class BookTableMetaData implements BaseColumns (public static final String TABLE_NAME = "books"; / / String public static final String BOOK_NAME = "name"; / / Stringpublic static final String BOOK_ISBN = "isbn"; / / Stringpublic static final String BOOK_AUTHOR = "author"; / / Integerpublic static final String CREATED_DATE = "created"; / / Integerpublic static final String MODIFIED_DATE = "modified"; public static final Uri CONTENT_URI = Uri.parse ( "content: / /" + AUTHORITY + " / books ");//-- multi-record public static final String CONTENT_TYPE = "vnd.android.cursor.dir / vnd.androidbook.book ";//-- a single record of public static final String CONTENT_ITEM_TYPE =" vnd.android. cursor.item / vnd.androidbook.book "; public static final String DEFAULT_SORT_ORDER =" modified DESC ";)) |
MainActivity.java
1 | package tl.android.apps; import tl.android.data.TestContentProvider; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.os . Bundle; public class MainActivity extends Activity (/ ** Called when the activity is first created. * / @ Override public void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.main); ContentResolver cr = this.getContentResolver (); ContentValues cv = new ContentValues (); cv.put ( "name", "android pro"); cr.insert (TestContentProvider.CONTENT_URI, cv); cv.put ( "name", "android programming "); cr.insert (TestContentProvider.CONTENT_URI, cv);)) |
AndroidManifest.xml
1 | <? xml version = "1.0" encoding = "utf-8"?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "tl.android.apps" android : versionCode = "1" android: versionName = "1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android: name = "tl.android.apps. MainActivity "android: label =" @ string / app_name "> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android: name =" android.intent.category.LAUNCHER " /> </ intent-filter> </ activity> <provider android:authorities="tl.android.provider.bookprovider"android:name="tl.android.data.TestContentProvider"> </ provider> </ application> < uses-sdk android: minSdkVersion = "4" /> </ manifest> |
17 Dec
Posted by support as General 541 views, 0 Comments
1 | HelloFormStuff. Java code is as follows |
1 | package com.example.test; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.Toast; import android.widget.ToggleButton; public class HelloFormStuff extends Activity (/ ** Called when the activity is first created. * / @ Override public void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.main); final ImageButton button = (ImageButton) findViewById (R.id.android_button); button.setOnClickListener (new View.OnClickListener () (public void onClick (View v) (/ / Perform action on clicks Toast.makeText (HelloFormStuff.this, "Beep Bop", Toast.LENGTH_SHORT). show ();))); final EditText edittext = (EditText) findViewById (R. id.edittext); edittext.setOnKeyListener (new View.OnKeyListener () (public boolean onKey (View v, int keyCode, KeyEvent event) (if ((event.getAction () == KeyEvent.ACTION_DOWN) & & (keyCode == KeyEvent . KEYCODE_ENTER)) (/ / Perform action on key press Toast.makeText (HelloFormStuff.this, edittext.getText (), Toast.LENGTH_SHORT). show (); return true;) return false;))); final CheckBox checkbox = (CheckBox) findViewById (R.id.checkbox); checkbox.setOnClickListener (new View.OnClickListener () (public void onClick (View v) (/ / Perform action on clicks if (checkbox.isChecked ()) (Toast.makeText ( HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT). show ();) else (Toast.makeText (HelloFormStuff.this, "Not selected", Toast.LENGTH_SHORT). show ();)))); View.OnClickListener radio_listener = new View.OnClickListener () (public void onClick (View v) (/ / Perform action on clicks RadioButton rb = (RadioButton) v; Toast.makeText (HelloFormStuff.this, rb.getText (), Toast.LENGTH_SHORT). show ();)); final RadioButton radio_red = (RadioButton) findViewById (R.id.radio_red); final RadioButton radio_blue = (RadioButton) findViewById (R.id.radio_blue); radio_red.setOnClickListener (radio_listener); radio_blue.setOnClickListener ( radio_listener); final ToggleButton togglebutton = (ToggleButton) findViewById (R.id.togglebutton); togglebutton.setOnClickListener (new View.OnClickListener () (public void onClick (View v) (/ / Perform action on clicks if (togglebutton.isChecked ( )) (Toast.makeText (HelloFormStuff.this, "ON", Toast.LENGTH_SHORT). show ();) else (Toast.makeText (HelloFormStuff.this, "OFF", Toast.LENGTH_SHORT). show ();)) ));)) |
layout-> main.xml
1 | <? xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: orientation = "vertical" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <ImageButton android: id = "@ + id / android_button" android: layout_width = "100dip" android: layout_height = "wrap_content" android: src = "@ drawable / android" / > <EditText android:id="@+id/edittext" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <CheckBox android: id = "@ + id / checkbox" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "check it out" /> <RadioGroup android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton android: id = "@ + id / radio_red "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: text =" Red "/> <RadioButton android: id =" @ + id / radio_blue "android: layout_width =" wrap_content "android: layout_height = "wrap_content" android: text = "Blue" /> </ RadioGroup> <ToggleButton android:id="@+id/togglebutton" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </ LinearLayout " |
run it as follows:
