android in practice_Using standard ContentProviders(AutoForm)

android in practice_Using standard ContentProviders(AutoForm)_第1张图片

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.autoform"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".RegistrationActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
	<uses-permission android:name="android.permission.READ_CONTACTS"/>
</manifest>

create class Contact.class

package example.autoform;

public class Contact {
	    public String phone = "";
	    public String firstName = "";
	    public String lastName = "";
	    public String email = "";
	    public String id = "";
	    @Override
	    public String toString(){
	        return firstName + " " + lastName + " " + phone + " " + email;
	    }
}

create class ContactManager:

public class ContactManager {
	   //use ContentResolver to query
		private final ContentResolver resolver;
	    public ContactManager(ContentResolver cr){
	        resolver = cr;
	    }
	    public Contact getContact(Contact partial){
	    	Contact contact=new Contact();
	    	contact.id=partial.id;
	    	contact.phone=partial.phone;
	    	String[] projection=new String[]{
	    			StructuredName.GIVEN_NAME,
	    			StructuredName.FAMILY_NAME,
	    			StructuredName.RAW_CONTACT_ID,
	    			StructuredName.CONTACT_ID
	    	};
	    	String selection=StructuredName.CONTACT_ID+"? AND"+Data.MIMETYPE+"='"+StructuredName.CONTENT_ITEM_TYPE+"'";
	    	String[] selectionArgs=new String[]{contact.id};
	    	Cursor nameCursor=null;
	    	try{
	    		nameCursor=resolver.query(Data.CONTENT_URI, projection, selection, selectionArgs, null);
	    		if(nameCursor.moveToFirst()){
	    			contact.firstName=nameCursor.getString(nameCursor.getColumnIndex(StructuredName.GIVEN_NAME));
	    			contact.lastName=nameCursor.getString(nameCursor.getColumnIndex(StructuredName.FAMILY_NAME));
	    		}
	    	}finally{
	    		if(nameCursor!=null){
	    			nameCursor.close();
	    		}
	    	}
	    	projection=new String[]{Email.DATA1,Email.CONTACT_ID};
	    	selection=Email.CONTACT_ID+"=?";
	    	Cursor emailCursor=null;
	    	try{
	    		emailCursor=resolver.query(Email.CONTENT_URI, projection, selection, selectionArgs, null);
	    		if(emailCursor.moveToFirst()){
	    			contact.email=emailCursor.getString(emailCursor.getColumnIndex(Email.DATA1));
	    		}
	    	}finally{
	    		if(emailCursor!=null)
	    			emailCursor.close();
	    	}
	    	return contact;
	    }

	    
	    public ArrayList<Contact> findByPhoneSubString(String phoneSubStr){
	    	ArrayList<Contact> contacts=new ArrayList<Contact>();
	    	String[] projection={Phone.CONTACT_ID,Phone.NUMBER};
	    	String selection=Data.IN_VISIBLE_GROUP+"=1 AND"+Phone.NUMBER+"LIKE?";
	    	String[] selectionArgs={"%"+phoneSubStr+"%"};
	    	if(phoneSubStr==null){
	    		selection=null;
	    		selectionArgs=null;
	    	}
	    	Cursor phoneCursor=null;
	    	try{
	    		//execute
	    		phoneCursor=resolver.query(Phone.CONTENT_URI, projection, selection, selectionArgs, null);
	    		int idCol=phoneCursor.getColumnIndex(Phone.CONTACT_ID);
	    		int numCol=phoneCursor.getColumnIndex(Phone.NUMBER);
	    		//iterate over result set
	    		while(phoneCursor.moveToNext()){
	    			long id=phoneCursor.getLong(idCol);
	    			String phoneNum=phoneCursor.getString(numCol);
	    			Contact contact=new Contact();
	    			contact.id=String.valueOf(id);
	    			contact.phone=phoneNum;
	    			contacts.add(contact);
	    		}
	    		
	    	}finally{
	    		if(phoneCursor!=null)
	    			phoneCursor.close();
	    	}
	    	
	    	return contacts;
	    }
}

create activity class RegistrationActivity:

public class RegistrationActivity extends Activity {
	 TextView first;
	 TextView last;
	 TextView email;
	 AutoCompleteTextView phone;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        first = (TextView)findViewById(R.id.entry_first_name);
        last = (TextView)findViewById(R.id.entry_last_name);
        email = (TextView)findViewById(R.id.entry_email);
        phone = (AutoCompleteTextView)findViewById(R.id.entry_phone);
        phone.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable textInput) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,int count) {
				// TODO Auto-generated method stub
				if(s.length()==2){
					PhoneLookupTask task=new PhoneLookupTask();
					task.execute(s.toString());
				}
				
			} 
        });
        email.setOnEditorActionListener(new OnEditorActionListener(){

			@Override
			public boolean onEditorAction(TextView v, int actionId,KeyEvent event) {
				// TODO Auto-generated method stub
				submitForm();
				return true;
			}
        	
        });
        Button doneButton = (Button)this.findViewById(R.id.done);
        doneButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				submitForm();
			}
        	
        });
      
    }
    class PhoneLookupTask extends AsyncTask<String,Void,ArrayList<Contact>>{
    	Context context=RegistrationActivity.this;
		@Override
		protected ArrayList<Contact> doInBackground(String... args) {
			ContactManager mgr=new ContactManager(context.getContentResolver());
			if(args.length==0){
				return mgr.findByPhoneSubString(null);
			}
			return mgr.findByPhoneSubString(args[0]);
		}
		
		protected void onPostExecute(ArrayList<Contact> result){
			final HashMap<String,Contact> phoneMap=new HashMap<String,Contact>();
			final String[] phonesList=new String[result.size()];
			for(int i=0;i<result.size();i++){
				Contact oc=result.get(i);
				phonesList[i]=removeFormat(oc.phone);
				phoneMap.put(removeFormat(oc.phone), oc);
			}
			ArrayAdapter<String> phoneAdapter=new ArrayAdapter<String>(context,R.layout.phone_suggest,phonesList);
			phone.setAdapter(phoneAdapter);
			phone.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> autoCompleteView, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					String phoneNum=(String)autoCompleteView.getItemAtPosition(position);
					Contact contact=phoneMap.get(phoneNum);
					if(contact!=null){
						ContactDetailLookupTask task=new ContactDetailLookupTask();
						task.execute(contact);
					}
				}
				
			});
		}
    }
    
    protected void submitForm(){
        InputMethodManager mgr=(InputMethodManager)this.getSystemService(INPUT_METHOD_SERVICE);
    	mgr.hideSoftInputFromInputMethod(first.getApplicationWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
    	Contact contact=new Contact();
    	contact.firstName=first.getText().toString();
    	contact.lastName=last.getText().toString();
    	contact.email=email.getText().toString();
    	contact.phone=phone.getText().toString();
    	Toast.makeText(this, "Contact submited"+contact, Toast.LENGTH_LONG).show();
    	Handler h=new Handler();
    	h.postDelayed(new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				finish();
			}
    		
    	}, 5000L);
    }
    
    static String removeFormat(String phone){
		if(phone==null){
			return null;
		}
		StringBuffer num=new StringBuffer();
		for(char ch:phone.toCharArray()){
			num.append(ch);
		}
		return num.toString();
    	
    }
    
    class ContactDetailLookupTask extends AsyncTask<Contact,Void,Contact>{
		@Override
		protected Contact doInBackground(Contact... params) {
			// TODO Auto-generated method stub
			ContactManager mgr=new ContactManager(getContentResolver());
			return mgr.getContact(params[0]);
		}
		
		protected void onPostExecute(Contact contact){
			  if (contact == null){
	                return;
	            }
	            if (!TextUtils.isEmpty(contact.firstName)) {
	                first.setText(contact.firstName);
	            } else {
	                first.setText("");
	            }
	            if (!TextUtils.isEmpty(contact.lastName)) {
	                last.setText(contact.lastName);
	            } else {
	                last.setText("");
	            }
	            if (!TextUtils.isEmpty(contact.email)) {
	                email.setText(contact.email);
	            } else {
	                email.setText("");
	            }
		}
    	
    }
}

use this ContentProvider to get the list of phone numbers for the AutoCompleteTextView

You can check the android.os.Build.VERSION at runtime to determine what version of the OS is running on the user’s phone, and pick the appropriate provider.

Android 3.0, a new constant was added to ContactsContract.CommonDataKinds. Email: ADDRESS. Its value is the same as Email.DATA1


valuse\colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="app_background">#dee6ed</color>
  <color name="header">#6f7bb0</color>
  <color name="subheader">#b2bcdf</color>
  <color name="module_background">#f8f8f9</color>
  <color name="bubble_bg">#ffffff</color>
  <color name="table_view_bg">#ffffff</color>
  <color name="call_to_action">#f5f4b6</color>
  <color name="background_selected">#848fcf</color>
  <color name="white">#ffffff</color>
  <color name="black">#000000</color>
  <color name="dark_gray">#222222</color>
  <color name="gray">#888888</color>
  <color name="light_gray">#a8a8a8</color>
  <color name="blue_text">#0000ff</color>
  <color name="blue_title_text">#3d588a</color>
  <color name="myinfo_edit_bg">#fffefdd9</color>
  <color name="myinfo_card_border">#fff14b66</color>
  <color name="photo_selected_border_color">#ffff7f24</color>
  <color name="warming_up">#ffea8030</color>
  <!--
  Use android transparent to avoid a bug where background set to transparent shows an image instead:
  Stack overflow here:http://stackoverflow.com/questions/3822123/weird-layout-problem-please-see-the-attached-image
  -->
  <color name="transparent">@android:color/transparent</color>
</resources>

valuse\strings.xml

<resources>
    <string name="app_name">AutoForm</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
     <string name="label_enter_your_info">
      Enter your contact info to get started
    </string>
    <string name="label_first_name">First name</string>
    <string name="label_phone_number">Your phone number</string>
    <string name="label_last_name">Last</string>
    <string name="label_email_address">Email address</string>
    <string name="done">Done</string>
</resources>

layout\main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/app_background"
  android:orientation="vertical">
  <TextView android:padding="10dp"
    android:layout_height="wrap_content"
    android:id="@+id/enter_info_prompt"
    android:text="@string/label_enter_your_info"
    android:layout_width="match_parent"
    android:background="@color/header"
    android:textColor="@color/white"
    android:textStyle="bold"
    android:textSize="15sp"
  />
	<ScrollView android:layout_width="match_parent"
	  android:layout_height="match_parent">
		<LinearLayout android:layout_width="match_parent"
		  android:layout_height="match_parent"
		  android:background="@color/app_background"
		  android:orientation="vertical">
		   <LinearLayout android:orientation="vertical"
		    android:layout_height="wrap_content"
		    android:layout_width="match_parent"
		    android:paddingTop="5dp"
		    android:paddingLeft="10dp"
		    android:paddingRight="10dp">
		    <TextView android:layout_height="wrap_content"
		      android:textSize="15sp"
		      android:layout_width="wrap_content"
		      android:padding="5dp"
		      android:textColor="@color/dark_gray"
		      android:text="@string/label_phone_number"
		    />
		    <AutoCompleteTextView android:layout_height="wrap_content"
		      android:layout_width="match_parent"
		      android:id="@+id/entry_phone"
		      android:textStyle="bold"
		      android:inputType="phone"
		      android:imeOptions="actionNext"
		    />
		  </LinearLayout>
		   <LinearLayout
		    android:layout_height="wrap_content"
		    android:layout_width="match_parent">
		    <LinearLayout
		      android:paddingTop="5dp"
		      android:paddingLeft="10dp"
		      android:paddingRight="10dp"
		      android:layout_weight="1"
		      android:layout_height="wrap_content"
		      android:layout_width="match_parent"
		      android:orientation="vertical">
		      <TextView
		        android:layout_height="wrap_content"
		        android:textSize="15sp"
		        android:layout_width="wrap_content"
		        android:padding="5dp"
		        android:textColor="@color/dark_gray"
		        android:text="@string/label_first_name"/>
		      <EditText
		        android:layout_height="wrap_content"
		        android:layout_width="match_parent"
		        android:id="@+id/entry_first_name"
		        android:textStyle="bold"
		        android:capitalize="words"
		        android:imeOptions="actionNext"
		        android:inputType="textCapWords"
		        android:nextFocusDown="@+id/entry_last_name"
		        />
		    </LinearLayout>
		    <LinearLayout
		      android:paddingTop="5dp"
		      android:paddingLeft="10dp"
		      android:paddingRight="10dp"
		      android:layout_weight="1"
		      android:layout_height="wrap_content"
		      android:layout_width="match_parent"
		      android:orientation="vertical">
		      <TextView
		        android:layout_height="wrap_content"
		        android:textSize="15sp"
		        android:layout_width="wrap_content"
		        android:padding="5dp"
		        android:textColor="@color/dark_gray"
		        android:text="@string/label_last_name"/>
		      <EditText
		        android:layout_height="wrap_content"
		        android:layout_width="match_parent"
		        android:id="@+id/entry_last_name"
		        android:textStyle="bold"
		        android:capitalize="words"
		        android:inputType="textCapWords"
		        android:imeOptions="actionNext"        
		        />        
		    </LinearLayout>  
		  </LinearLayout>
		  <LinearLayout
		    android:paddingTop="5dp"
		    android:paddingLeft="10dp"
		    android:paddingRight="10dp"
		    android:layout_height="wrap_content"
		    android:layout_width="match_parent"
		    android:orientation="vertical">
		    <TextView
		      android:layout_height="wrap_content"
		      android:textSize="15sp"
		      android:layout_width="wrap_content"
		      android:padding="5dp"
		      android:textColor="@color/dark_gray"
		      android:text="@string/label_email_address"/>
		    <EditText
		      android:layout_height="wrap_content"
		      android:layout_width="match_parent"
		      android:id="@+id/entry_email"
		      android:textStyle="bold"
		      android:inputType="textEmailAddress"
		      android:imeOptions="actionGo"
		      />
		  </LinearLayout>
		  <Button
		    android:layout_height="wrap_content"
		    android:layout_gravity="right"
		    android:layout_width="wrap_content"
		    android:id="@+id/done"
		    android:layout_margin="15dp"
		    android:textColor="@color/white"
		    android:text="@string/done"
		    android:minWidth="100dp"
		    android:textStyle="bold"
		    android:textSize="15sp"
		  />
		</LinearLayout>
</ScrollView>  
</LinearLayout>

\layout\phone_suggest.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:textColor="@color/blue_text"
  android:textSize="15dp"
  >
</TextView>


你可能感兴趣的:(android in practice_Using standard ContentProviders(AutoForm))