Android程序示例
Android代码示例
OptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
TextView label = (TextView)findViewById(R.id.label);
switch (item.getItemId()) {
case R.id.main_menu_0:
label.setText("打印,菜单ID:" + item.getItemId());
return true;
case R.id.main_menu_1:
label.setText("新建,菜单ID:" + item.getItemId());
return true;
case R.id.main_menu_2:
label.setText("邮件,菜单ID:" + item.getItemId());
return true;
case R.id.main_menu_3:
label.setText("设置,菜单ID:" + item.getItemId());
return true;
case R.id.main_menu_4:
label.setText("订阅,菜单ID:" + item.getItemId());
return true;
default:
return false;
}
}
全体文件:
public class OptionMenu2Activity extends Activity {
final static int MENU_00 = Menu.FIRST;
final static int MENU_01 = Menu.FIRST+1;
final static int MENU_02 = Menu.FIRST+2;
final static int MENU_03 = Menu.FIRST+3;
final static int MENU_04 = Menu.FIRST+4;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,MENU_00,0,"打印").setIcon(R.drawable.pic0);
menu.add(0,MENU_01,1,"新建").setIcon(R.drawable.pic1);
menu.add(0,MENU_02,2,"邮件").setIcon(R.drawable.pic2);
menu.add(0,MENU_03,3,"设置").setIcon(R.drawable.pic3);
menu.add(0,MENU_04,4,"订阅").setIcon(R.drawable.pic4);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
TextView label = (TextView)findViewById(R.id.label);
switch (item.getItemId()) {
case MENU_00:
label.setText("打印,菜单ID:" + item.getItemId());
return true;
case MENU_01:
label.setText("新建,菜单ID:" + item.getItemId());
return true;
case MENU_02:
label.setText("邮件,菜单ID:" + item.getItemId());
return true;
case MENU_03:
label.setText("设置,菜单ID:" + item.getItemId());
return true;
case MENU_04:
label.setText("订阅,菜单ID:" + item.getItemId());
return true;
default:
return false;
}
}
}
ImageButton
imageButton.setImageResource(R.drawable.download);
imageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
textView.setText("ImageButtonTest");
}
});
CheckBox & RadioButton
- checkBox
final CheckBox checkBox1= (CheckBox)findViewById(R.id.CheckBox01);
final CheckBox checkBox2= (CheckBox)findViewById(R.id.CheckBox02);
CheckBox.OnClickListener checkboxListener = new CheckBox.OnClickListener(){
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.CheckBox01:
textView.setText("CheckBox01, isChecked:"+String.valueOf(checkBox1.isChecked()));
return;
case R.id.CheckBox02:
textView.setText("CheckBox02, isChecked:"+String.valueOf(checkBox2.isChecked()));
return;
}
}};
checkBox1.setOnClickListener(checkboxListener);
checkBox2.setOnClickListener(checkboxListener);
- RadioButton
final RadioButton radioButton1 = (RadioButton)findViewById(R.id.RadioButton01);
final RadioButton radioButton2 = (RadioButton)findViewById(R.id.RadioButton02);
RadioButton.OnClickListener radioButtonListener = new RadioButton.OnClickListener(){
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.RadioButton01:
textView.setText("RadioButton1 is selected");
return;
case R.id.RadioButton02:
textView.setText("RadioButton2 is selected");;
return;
}
}};
radioButton1.setOnClickListener(radioButtonListener);
radioButton2.setOnClickListener(radioButtonListener);
Context Menu快捷菜单
public class ContextMenuActivity extends Activity {
/** Called when the activity is first created. */
final static int CONTEXT_MENU_1 = Menu.FIRST;
final static int CONTEXT_MENU_2 = Menu.FIRST+1;
final static int CONTEXT_MENU_3 = Menu.FIRST+2;
TextView LabelView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LabelView = (TextView)findViewById(R.id.label);
LabelView.setText(Html.fromHtml("<font color=\"#ff0000\">红色</font>其它颜色"));
registerForContextMenu(LabelView);
}
@Override
public void onCreateContextMenu(ContextMenu menu,
View v, ContextMenuInfo menuInfo){
menu.setHeaderTitle("快捷菜单标题");
menu.add(0, CONTEXT_MENU_1, 0,"菜单子项1");
menu.add(0, CONTEXT_MENU_2, 1,"菜单子项2");
menu.add(0, CONTEXT_MENU_3, 2,"菜单子项3");
}
@Override
public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case CONTEXT_MENU_1:
LabelView.setText("菜单子项1");
return true;
case CONTEXT_MENU_2:
LabelView.setText("菜单子项2");
return true;
case CONTEXT_MENU_3:
LabelView.setText("菜单子项3");
return true;
}
return false;
}
}
Key Event
public class KeyEventDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText entryText = (EditText)findViewById(R.id.entry);
final CheckBox checkBox = (CheckBox)findViewById(R.id.block);
final TextView labelView = (TextView)findViewById(R.id.label);
entryText.setOnKeyListener(new OnKeyListener(){
@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
int metaState = keyEvent.getMetaState();
int unicodeChar = keyEvent.getUnicodeChar();
String msg = "";
msg +="按键动作:" + String.valueOf(keyEvent.getAction())+"\n";
msg +="按键代码:" + String.valueOf(keyCode)+"\n";
msg +="按键字符:" + (char)unicodeChar+"\n";
msg +="UNICODE:" + String.valueOf(unicodeChar)+"\n";
msg +="重复次数:" + String.valueOf(keyEvent.getRepeatCount())+"\n";
msg +="功能键状态:" + String.valueOf(metaState)+"\n";
msg +="硬件编码:" + String.valueOf(keyEvent.getScanCode())+"\n";
msg +="按键标志:" + String.valueOf(keyEvent.getFlags())+"\n";
labelView.setText(msg);
if (checkBox.isChecked())
return true;
else
return false;
}
});
}
}
ListView Demo
public class ListViewDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView)findViewById(R.id.TextView01);
ListView listView = (ListView)findViewById(R.id.ListView01);
List<String> list = new ArrayList<String>();
list .add("ListView子项1");
list .add("ListView子项2");
list .add("ListView子项3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list );
listView.setAdapter(adapter);
AdapterView.OnItemClickListener listViewListener = new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String msg = "父View:"+arg0.toString()+"\n"+
"子View:"+arg1.toString()+"\n"+
"位置:"+String.valueOf(arg2)+",ID:"+String.valueOf(arg3);
textView.setText(msg);
}};
listView.setOnItemClickListener(listViewListener);
}
}
Sub menu 子菜单
package edu.hrbeu.SubMenu2;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.TextView;
public class SubMenu2Activity extends Activity {
final static int MENU_00 = Menu.FIRST;
final static int MENU_01 = Menu.FIRST+1;
final static int SUB_MENU_00_01 = Menu.FIRST+2;
final static int SUB_MENU_01_00 = Menu.FIRST+3;
final static int SUB_MENU_01_01 = Menu.FIRST+4;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu sub1 = (SubMenu) menu.addSubMenu(0,MENU_00,0,"设置")
.setHeaderIcon(R.drawable.pic3);
sub1.add(0,SUB_MENU_00_01 ,0,"打印").setIcon(R.drawable.pic0);
SubMenu sub2 = (SubMenu) menu.addSubMenu(0,MENU_01,1,"新建")
.setHeaderIcon(R.drawable.pic1);
sub2.add(0,SUB_MENU_01_00 ,0,"邮件").setIcon(R.drawable.pic2);
sub2.add(0,SUB_MENU_01_01 ,0,"订阅").setIcon(R.drawable.pic4);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
TextView label = (TextView)findViewById(R.id.label);
switch (item.getItemId()) {
case MENU_00:
label.setText("设置,菜单ID:" + item.getItemId());
return true;
case MENU_01:
label.setText("新建,菜单ID:" + item.getItemId());
return true;
case SUB_MENU_00_01:
label.setText("打印,子菜单ID:" + item.getItemId());
return true;
case SUB_MENU_01_00:
label.setText("邮件,子菜单ID:" + item.getItemId());
return true;
case SUB_MENU_01_01:
label.setText("订阅,子菜单ID:" + item.getItemId());
return true;
default:
return false;
}
}
}
Activity Communication
ActivityCommunication.java
package edu.hrbeu.ActivityCommunication;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ActivityCommunicationActivity extends Activity {
private static final int SUBACTIVITY1 = 1;
private static final int SUBACTIVITY2 = 2;
TextView textView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textShow);
final Button btn1 = (Button)findViewById(R.id.btn1);
final Button btn2 = (Button)findViewById(R.id.btn2);
btn1.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(ActivityCommunicationActivity.this, SubActivity1.class);
startActivityForResult(intent, SUBACTIVITY1);
}
});
btn2.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(ActivityCommunicationActivity.this, SubActivity2.class);
startActivityForResult(intent, SUBACTIVITY2);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case SUBACTIVITY1:
if (resultCode == RESULT_OK){
Uri uriData = data.getData();
textView.setText(uriData.toString());
}
break;
case SUBACTIVITY2:
break;
}
}
}
SubActivity1.java
package edu.hrbeu.ActivityCommunication;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SubActivity1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subactivity1);
final EditText editText = (EditText)findViewById(R.id.edit);
Button btnOK = (Button)findViewById(R.id.btn_ok);
Button btnCancel = (Button)findViewById(R.id.btn_cancel);
btnOK.setOnClickListener(new OnClickListener(){
public void onClick(View view){
String uriString = editText.getText().toString();
Uri data = Uri.parse(uriString);
Intent result = new Intent(null, data);
setResult(RESULT_OK, result);
finish();
}
});
btnCancel.setOnClickListener(new OnClickListener(){
public void onClick(View view){
setResult(RESULT_CANCELED, null);
finish();
}
});
}
}
SubActivity2.java
package edu.hrbeu.ActivityCommunication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SubActivity2 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subactivity2);
Button btnReturn = (Button)findViewById(R.id.btn_return);
btnReturn.setOnClickListener(new OnClickListener(){
public void onClick(View view){
setResult(RESULT_CANCELED, null);
finish();
}
});
}
}
BroadcastReceiverDemo
BroadcastReceiverDemoActivity.java
package edu.hrbeu.BroadcastReceiverDemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class BroadcastReceiverDemoActivity extends Activity {
private EditText entryText ;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
entryText = (EditText)findViewById(R.id.entry);
button = (Button)findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Intent intent = new Intent("HELLO");
intent.putExtra("message", entryText.getText().toString());
sendBroadcast(intent);
}
});
}
}
MyBroadcastReceiver.java
package edu.hrbeu.BroadcastReceiverDemo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("message");
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}
Intent Demo
IntentDemoActivity.java
package edu.hrbeu.IntentDemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class IntentDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(IntentDemoActivity.this, NewActivity.class);
startActivity(intent);
}
});
}
}
NewActivity.java
package edu.hrbeu.IntentDemo;
import android.app.Activity;
import android.os.Bundle;
public class NewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_2);
}
}
IntentResolutionDemo
IntentResutionDemoActivity.java
package edu.hrbeu.IntentResolutionDemo;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class IntentResolutionDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("schemodemo://edu.hrbeu/path"));
startActivity(intent);
}
});
}
}
NewActivity.java
package edu.hrbeu.IntentResolutionDemo;
import android.app.Activity;
import android.os.Bundle;
public class NewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_2);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.hrbeu.IntentResolutionDemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".IntentResolutionDemoActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="schemodemo" android:host="edu.hrbeu" />
</intent-filter>
</activity>
</application>
</manifest>
AIDL
a.aidl
package ImplicityRandomServiceDemo;
interface a{
long add(long b1,long b2);
}
ImplicityRandomServiceDemoActivity.java
package edu.hrbeu.ImplicityRandomServiceDemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ImplicityRandomServiceDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startButton = (Button)findViewById(R.id.start);
Button stopButton = (Button)findViewById(R.id.stop);
final Intent serviceIntent = new Intent();
serviceIntent.setAction("hh1");
startButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View view){
startService(serviceIntent);
}
});
stopButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View view){
stopService(serviceIntent);
}
});
}
}
RandomService.java
package edu.hrbeu.ImplicityRandomServiceDemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class RandomService extends Service{
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "(1) 调用onCreate()",
Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "(2) 调用onStart()",
Toast.LENGTH_SHORT).show();
double randomDouble = Math.random();
String msg = "随机数:"+ String.valueOf(randomDouble);
Toast.makeText(this,msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "(3) 调用onDestroy()",
Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
AIDL: RemoteMathCallerDemoActivity
RemoteMathCallerDemoActivity.java
package edu.hrbeu.RemoteMathCallerDemo;
import edu.hrbeu.RemoteMathServiceDemo.IMathService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class RemoteMathCallerDemoActivity extends Activity {
private IMathService mathService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mathService = IMathService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mathService = null;
}
};
private boolean isBound = false;
TextView labelView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
labelView = (TextView)findViewById(R.id.label);
Button bindButton = (Button)findViewById(R.id.bind);
Button unbindButton = (Button)findViewById(R.id.unbind);
Button computButton = (Button)findViewById(R.id.compute_add);
bindButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(!isBound){
final Intent serviceIntent = new Intent();
serviceIntent.setAction("edu.hrbeu.RemoteMathServiceDemo.MathService");
bindService(serviceIntent,mConnection,Context.BIND_AUTO_CREATE);
isBound = true;
}
}
});
unbindButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(isBound){
isBound = false;
unbindService(mConnection);
mathService = null;
}
}
});
computButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (mathService == null){
labelView.setText("δ��Զ�̷���");
return;
}
long a = Math.round(Math.random()*100);
long b = Math.round(Math.random()*100);
long result = 0;
try {
result = mathService.Add(a, b);
} catch (RemoteException e) {
e.printStackTrace();
}
String msg = String.valueOf(a)+" + "+String.valueOf(b)+
" = "+String.valueOf(result);
labelView.setText(msg);
}
});
}
}
IMathService.aidl
package edu.hrbeu.RemoteMathServiceDemo;
interface IMathService {
long Add(long a, long b);
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.hrbeu.RemoteMathCallerDemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".RemoteMathCallerDemoActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ContentProvider Demo
contentProvider.java
package edu.hrbeu.ContentProviderDemo;
import android.content.ContentProvider;
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;
public class PeopleProvider extends ContentProvider{
private static final String DB_NAME = "people.db";
private static final String DB_TABLE = "peopleinfo";
private static final int DB_VERSION = 1;
private SQLiteDatabase db;
private DBOpenHelper dbOpenHelper;
private static final int MULTIPLE_PEOPLE = 1;
private static final int SINGLE_PEOPLE = 2;
private static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(People.AUTHORITY, People.PATH_MULTIPLE, MULTIPLE_PEOPLE);
uriMatcher.addURI(People.AUTHORITY, People.PATH_SINGLE, SINGLE_PEOPLE);
}
@Override
public String getType(Uri uri) {
switch(uriMatcher.match(uri)){
case MULTIPLE_PEOPLE:
return People.MINE_TYPE_MULTIPLE;
case SINGLE_PEOPLE:
return People.MINE_TYPE_SINGLE;
default:
throw new IllegalArgumentException("Unkown uri:"+uri);
}
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch(uriMatcher.match(uri)){
case MULTIPLE_PEOPLE:
count = db.delete(DB_TABLE, selection, selectionArgs);
break;
case SINGLE_PEOPLE:
String segment = uri.getPathSegments().get(1);
count = db.delete(DB_TABLE, People.KEY_ID + "=" + segment, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI:" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long id = db.insert(DB_TABLE, null, values);
if ( id > 0 ){
Uri newUri = ContentUris.withAppendedId(People.CONTENT_URI, id);
getContext().getContentResolver().notifyChange(newUri, null);
return newUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
@Override
public boolean onCreate() {
Context context = getContext();
dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
db = dbOpenHelper.getWritableDatabase();
if (db == null)
return false;
else
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(DB_TABLE);
switch(uriMatcher.match(uri)){
case SINGLE_PEOPLE:
qb.appendWhere(People.KEY_ID + "=" + uri.getPathSegments().get(1));
break;
default:
break;
}
Cursor cursor = qb.query(db,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count;
switch(uriMatcher.match(uri)){
case MULTIPLE_PEOPLE:
count = db.update(DB_TABLE, values, selection, selectionArgs);
break;
case SINGLE_PEOPLE:
String segment = uri.getPathSegments().get(1);
count = db.update(DB_TABLE, values, People.KEY_ID+"="+segment, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknow URI:" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
private static class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
private static final String DB_CREATE = "create table " +
DB_TABLE + " (" + People.KEY_ID + " integer primary key autoincrement, " +
People.KEY_NAME+ " text not null, " + People.KEY_AGE+ " integer," + People.KEY_HEIGHT + " float);";
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
_db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(_db);
}
}
}
People.java
package edu.hrbeu.ContentProviderDemo;
import android.net.Uri;
public class People{
public static final String MIME_DIR_PREFIX = "vnd.android.cursor.dir";
public static final String MIME_ITEM_PREFIX = "vnd.android.cursor.item";
public static final String MINE_ITEM = "vnd.hrbeu.people";
public static final String MINE_TYPE_SINGLE = MIME_ITEM_PREFIX + "/" + MINE_ITEM;
public static final String MINE_TYPE_MULTIPLE = MIME_DIR_PREFIX + "/" + MINE_ITEM;
public static final String AUTHORITY = "edu.hrbeu.peopleprovider";
public static final String PATH_SINGLE = "people/#";
public static final String PATH_MULTIPLE = "people";
public static final String CONTENT_URI_STRING = "content://" + AUTHORITY + "/" + PATH_MULTIPLE;
public static final Uri CONTENT_URI = Uri.parse(CONTENT_URI_STRING);
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_AGE = "age";
public static final String KEY_HEIGHT = "height";
}
ContentResolverDemo
ContentResolverDemoActivtiy.java
People.java同上
SQLite Demo
DBAdapter.java
package edu.hrbeu.SQLiteDemo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class DBAdapter {
private static final String DB_NAME = "people.db";
private static final String DB_TABLE = "peopleinfo";
private static final int DB_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_AGE = "age";
public static final String KEY_HEIGHT = "height";
private SQLiteDatabase db;
private final Context context;
private DBOpenHelper dbOpenHelper;
public DBAdapter(Context _context) {
context = _context;
}
/** Close the database */
public void close() {
if (db != null){
db.close();
db = null;
}
}
/** Open the database */
public void open() throws SQLiteException {
dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
try {
db = dbOpenHelper.getWritableDatabase();
}
catch (SQLiteException ex) {
db = dbOpenHelper.getReadableDatabase();
}
}
public long insert(People people) {
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, people.Name);
newValues.put(KEY_AGE, people.Age);
newValues.put(KEY_HEIGHT, people.Height);
return db.insert(DB_TABLE, null, newValues);
}
public People[] queryAllData() {
Cursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT},
null, null, null, null, null);
return ConvertToPeople(results);
}
public People[] queryOneData(long id) {
Cursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT},
KEY_ID + "=" + id, null, null, null, null);
return ConvertToPeople(results);
}
private People[] ConvertToPeople(Cursor cursor){
int resultCounts = cursor.getCount();
if (resultCounts == 0 || !cursor.moveToFirst()){
return null;
}
People[] peoples = new People[resultCounts];
for (int i = 0 ; i<resultCounts; i++){
peoples[i] = new People();
peoples[i].ID = cursor.getInt(0);
peoples[i].Name = cursor.getString(cursor.getColumnIndex(KEY_NAME));
peoples[i].Age = cursor.getInt(cursor.getColumnIndex(KEY_AGE));
peoples[i].Height = cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT));
cursor.moveToNext();
}
return peoples;
}
public long deleteAllData() {
return db.delete(DB_TABLE, null, null);
}
public long deleteOneData(long id) {
return db.delete(DB_TABLE, KEY_ID + "=" + id, null);
}
public long updateOneData(long id , People people){
ContentValues updateValues = new ContentValues();
updateValues.put(KEY_NAME, people.Name);
updateValues.put(KEY_AGE, people.Age);
updateValues.put(KEY_HEIGHT, people.Height);
return db.update(DB_TABLE, updateValues, KEY_ID + "=" + id, null);
}
/** 静态Helper类,用于建立、更新和打开数据库*/
private static class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
private static final String DB_CREATE = "create table " +
DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " +
KEY_NAME+ " text not null, " + KEY_AGE+ " integer," + KEY_HEIGHT + " float);";
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
_db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(_db);
}
}
}
People.java
package edu.hrbeu.SQLiteDemo;
public class People {
public int ID = -1;
public String Name;
public int Age;
public float Height;
@Override
public String toString(){
String result = "";
result += "ID:" + this.ID + ",";
result += "姓名:" + this.Name + ",";
result += "年龄:" + this.Age + ", ";
result += "身高:" + this.Height + ",";
return result;
}
}
SQLiteDemoActivity.java
package edu.hrbeu.SQLiteDemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SQLiteDemoActivity extends Activity {
/** Called when the activity is first created. */
private DBAdapter dbAdepter ;
private EditText nameText;
private EditText ageText;
private EditText heightText;
private EditText idEntry;
private TextView labelView;
private TextView displayView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameText = (EditText)findViewById(R.id.name);
ageText = (EditText)findViewById(R.id.age);
heightText = (EditText)findViewById(R.id.height);
idEntry = (EditText)findViewById(R.id.id_entry);
labelView = (TextView)findViewById(R.id.label);
displayView = (TextView)findViewById(R.id.display);
Button addButton = (Button)findViewById(R.id.add);
Button queryAllButton = (Button)findViewById(R.id.query_all);
Button clearButton = (Button)findViewById(R.id.clear);
Button deleteAllButton = (Button)findViewById(R.id.delete_all);
Button queryButton = (Button)findViewById(R.id.query);
Button deleteButton = (Button)findViewById(R.id.delete);
Button updateButton = (Button)findViewById(R.id.update);
addButton.setOnClickListener(addButtonListener);
queryAllButton.setOnClickListener(queryAllButtonListener);
clearButton.setOnClickListener(clearButtonListener);
deleteAllButton.setOnClickListener(deleteAllButtonListener);
queryButton.setOnClickListener(queryButtonListener);
deleteButton.setOnClickListener(deleteButtonListener);
updateButton.setOnClickListener(updateButtonListener);
dbAdepter = new DBAdapter(this);
dbAdepter.open();
}
OnClickListener addButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
People people = new People();
people.Name = nameText.getText().toString();
people.Age = Integer.parseInt(ageText.getText().toString());
people.Height = Float.parseFloat(heightText.getText().toString());
long colunm = dbAdepter.insert(people);
if (colunm == -1 ){
labelView.setText("添加过程错误!");
} else {
labelView.setText("成功添加数据,ID:"+String.valueOf(colunm));
}
}
};
OnClickListener queryAllButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
People[] peoples = dbAdepter.queryAllData();
if (peoples == null){
labelView.setText("数据库中没有数据");
return;
}
labelView.setText("数据库:");
String msg = "";
for (int i = 0 ; i<peoples.length; i++){
msg += peoples[i].toString()+"\n";
}
displayView.setText(msg);
}
};
OnClickListener clearButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
displayView.setText("");
}
};
OnClickListener deleteAllButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
dbAdepter.deleteAllData();
String msg = "数据全部删除";
labelView.setText(msg);
}
};
OnClickListener queryButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
int id = Integer.parseInt(idEntry.getText().toString());
People[] peoples = dbAdepter.queryOneData(id);
if (peoples == null){
labelView.setText("数据库中没有ID为"+String.valueOf(id)+"的数据");
return;
}
labelView.setText("数据库:");
displayView.setText(peoples[0].toString());
}
};
OnClickListener deleteButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
long id = Integer.parseInt(idEntry.getText().toString());
long result = dbAdepter.deleteOneData(id);
String msg = "删除ID为"+idEntry.getText().toString()+"的数据" + (result>0?"成功":"失败");
labelView.setText(msg);
}
};
OnClickListener updateButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
People people = new People();
people.Name = nameText.getText().toString();
people.Age = Integer.parseInt(ageText.getText().toString());
people.Height = Float.parseFloat(heightText.getText().toString());
long id = Integer.parseInt(idEntry.getText().toString());
long count = dbAdepter.updateOneData(id, people);
if (count == -1 ){
labelView.setText("更新错误!");
} else {
labelView.setText("更新成功,更新数据"+String.valueOf(count)+"条");
}
}
};
}
Android程序示例的更多相关文章
- Android : 跟我学Binder --- (3) C程序示例
目录: Android : 跟我学Binder --- (1) 什么是Binder IPC?为何要使用Binder机制? Android : 跟我学Binder --- (2) AIDL分析及手动实现 ...
- java Android SDK安装与环境变量配置以及开发第一个Android程序
JAVA的安装与环境变量的配置 1.先下载JAVA,并且安装. 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk-7u3 ...
- 分析Android程序之破解第一个程序
破解Android程序通常的方法是将apk文件利用ApkTool反编译,生成Smali格式的反汇编代码,然后阅读Smali文件的代码来理解程序的运行机制,找到程序的突破口进行修改,最后使用ApkToo ...
- Android 程序框架设计
这篇文章主要内容来自于之前我讲的一个PPT文档,现在将其整理如下.欢迎指正.以下的内容都是来自于我自身的经验,欢迎大家多提自己的建议. 1.一些概念 模式的定义: 每个模式都描述了一个在我们的环境中不 ...
- 【Android实验】第一个Android程序与Activity生命周期
目录 第一个Android程序和Activity生命周期 实验目的 实验要求 实验过程 1. 程序正常启动与关闭 2. 外来电话接入的情况 3. 外来短信接入的情况 4. 程序运行中切换到其他程序(比 ...
- 比较windows phone程序启动和android程序启动原理
windows phone 程序是如何启动的了,他和android程序有什么区别,我们重点从native code 层面来分析 在windows phone 程序启动的时候是: 在XAML中使用应用程 ...
- Android 程序员必须知道的 53 个知识点
1. android 单实例运行方法 我们都知道 Android 平台没有任务管理器,而内部 App 维护者一个 Activity history stack 来实现窗口显示和销毁,对于常规从快捷方式 ...
- 用Ant手动打包android程序,android分包机制解决65536方法过多异常
Android利用ant手动打包 首先我们要给自己的IDE eclispe配置ant,默认的eclipse是集成了ant构建工具的,但是google提供的Android集成开发工具ADT,里面封装了E ...
- [zhuan]Android程序的真正入口Application
http://blog.csdn.net/coding_or_coded/article/details/6602560 接触android已经有一段时间了,一直以为android程序的入口是配置文件 ...
随机推荐
- MySQL找出锁等待
1.服务器级别的锁等待 可以通过show processlist看到等待锁的线程id,但是无法知道究竟哪个线程持有锁 可以通过mysqladmin debug 相关等待锁的线程以及谁持有锁可以在错误日 ...
- HTML方法
HTTP 方法:GET 对比 POST 两种最常用的 HTTP 方法是:GET 和 POST. 什么是 HTTP ? 超文本传输协议(HTTP)的设计目的是保证客户端与服务器之间的通信. HTTP 的 ...
- go for cryptocurrency
https://blog.conformal.com/category/btcd/ https://github.com/btcsuite/btcd/tree/master/docs https:// ...
- TCP/UDP client/server library for Java, 最好的java语言tcp udp 服务器客户端实现库
这个库andrdoi也可以用,而且是基于类的使用方式: 它支持类似聊天室的功能,即一个人说话,所有客户端都能收到,当然也支持点点通信.它还支持 RMI 的方式调用远程过程. https://githu ...
- 017-linux正则表达式
一.单字符表示:1.特定字符:某个具体的字符. '1' 'a' '\.'2.范围内单个字符:单个字符[] [0-9] [259] [a-z] [abc] [A-Z] [ABC] [a-zA-Z] [, ...
- EOJ Monthly 2018.11 猜价格 (模拟)
分三种情况: 1.k=1.此时每次都说反话,反着二分即可. 2.1<k <= n.那么在前n次问答中一定会出现一次错误,通过不断输出1找出那个错误发生的位置(若回答是>那这就是错误) ...
- EditPlus 4.3.2499 中文版已经发布(11月21日更新)
新的版本修复了如下问题: 文本库的日期快捷方式“^@”失效. 列选模式下“减少缩进量”命令无法执行. 在某些情况下突出显示匹配括号导致程序崩溃.(这个问题是我发现的,电邮告诉作者后,一天之内就修复了) ...
- 查看Tensorflow版本
python -c 'import tensorflow as tf; print(tf.__version__)' # for Python 2 python3 -c 'import tensorf ...
- Linux命令: 查找文件中的字符串
①cat filename | grep 'string' ②编辑模式查找,/string, 依次敲入下面的命令 vim filename e i ESC /string 从光标位置开始往后查找第一个 ...
- tomcat性能调优 大赞
从“第三天”的性能测试一节中,我们得知了决定性能测试的几个重要指标,它们是: ü 吞吐量 ü Responsetime ü Cpuload ü MemoryUsage 我 们也在第三天的学习中对Apa ...