当前位置:首页 > 服务端 > Android程序示例

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);
    }
}
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)+"条");	
				
			}
		}
    };

}

作者:pprp
来源链接:https://www.cnblogs.com/pprp/p/9998007.html

版权声明:
1、Java侠(https://www.javaxia.com)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaxia.com/server/125768.html

标签: android studio
分享给朋友: