Zhao yazhi _ Case Study of updating and deleting a phone book by using a content provider in android

Source: Internet
Author: User

Requirement Analysis:

Use ContentResolver to operate the data of the content provider, display the name and phone number in listView, and carry the add and delete buttons for corresponding operations

Steps:

    Adater model layer create content parser object ContentResolver define URI custom CursorAdapter implement constructor public MyCursorAapter (Context context, Cursor c, int flags) implement public View newView (Context context, Cursor cursor, viewGroup parent) method to implement public void bindView (View view, Context context, Cursor cursor)
      Set the display data query control for the adapter and set the control value to delete the data.
        ContentResolver's delete method deletes data
        Re-Initialize data update data new activity and layout file jump to activity through intent in MainActivity and upload the value at the corresponding position to the update interface to obtain the corresponding data jump to activity through intent send with startActivityForResult the return value lookup control of the data is assigned a value to the lookup control. The intent value is assigned to the control to create a content parser. The content parser updates the data uri declaration. The ContentValues value is used to place the result code and update the result. the value is returned to MainActivity. In MainActivity, The onActivityResult method is used to process the update successfully or fails. Use the content parser to initialize the data and set the adaptercontentResolver query method to find the data.
        Bind to view

        Main Interface for achieving results
        Delete bbb
        Click the updated interface.

        Update Data

        Updated page
        The main code contentprovider shares the same data as ContentProvider introduces http://blog.csdn.net/zhaoyazhi2129/article/details/29839561

        Layout file activity_main.xml
                
                      
             
            

        List_item_user.xml
            
                
                 
                 
                 
             
            
        Activity_user_update.xml
                
                     
                      
                  
                 
                     
                      
                          
                       
                  
                 
                     
                      
                          
                       
                  
                 
                     
                      
                          
                       
                  
                 
                     
                      
                          
                       
                  
                 
                          
                  
                 
            

        Main Program MainActivity. java
        Package com. example. android_provider; import android. app. activity; import android. content. contentResolver; import android. content. context; import android. content. intent; import android. content. pm. labeledIntent; import android. database. cursor; import android.net. uri; import android. OS. bundle; import android. support. v4.widget. cursorAdapter; import android. support. v4.widget. simpleCursorAdapter; import android. vi Ew. layoutInflater; import android. view. view; import android. view. view. onClickListener; import android. view. viewGroup; import android. widget. button; import android. widget. listView; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity {private ListView lv_user; // The content parser private ContentResolver contentResolver; // The operation flag private static final String AUTHORITIE =" Www.csdn.com. provider. userContentProvider "; // Request Code int requestUpdCode = 1; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // model layer // create content parser object contentResolver = getContentResolver (); lv_user = (ListView) findViewById (R. id. listView1); initData ();}/*** query data */private void initData () {// control layer (custom) Cursor c = contentResolve R. query (Uri. parse ("content: //" + AUTHORITIE + "/query"), new String [] {"userid as _ id", "username", "userage ", "usersalary", "userphone"}, null); MyCursorAapter adapter = new MyCursorAapter (this, c, CursorAdapter. FLAG_REGISTER_CONTENT_OBSERVER); // view layer lv_user.setAdapter (adapter) ;}@ Overrideprotected void onActivityResult (int requestCode, int resultCode, Intent data) {super. onActivityResult (RequestCode, resultCode, data); // Request Code if (requestCode = requestUpdCode) {// result code if (resultCode = 2) {// if (data. getIntExtra ("count", 0)> 0) {initData (); // reload the Toast interface. makeText (this, "updated successfully", 0 ). show ();} else {Toast. makeText (this, "update failed", 0 ). show () ;}}} class MyCursorAapter extends CursorAdapter {/// Context object private context Context context; // pump, layout service object private LayoutInflater mInflater; // constructor public MyCur SorAapter (Context context, Cursor c, int flags) {super (context, c, flags); this. context = context; mInflater = (LayoutInflater) context. getSystemService (Context. LAYOUT_INFLATER_SERVICE);} // The mInflater service returns a View control object through the inflate method. // It is a View object converted from its own layout file, after conversion, the current layout can be processed in bindView // new first. New to output the layout file for each entry. // New: the current layout is displayed. You can use findViewById in bindView to obtain the control @ Overridepublic View newView (Context context, Cursor cursor, ViewGroup parent) {return mInflater. inflate (R. layout. list_item_user, parent, false) ;}@ Overridepublic void bindView (View view, Context context, Cursor cursor) {// find the component Button btn_del = (Button) view. findViewById (R. id. btn_delete); Button btn_upd = (Button) view. findViewById (R. id. btn_update); TextView TV _ Name = (TextView) view. findViewById (R. id. TV _name); TextView TV _phone = (TextView) view. findViewById (R. id. TV _phone); // set the value TV _name.setText (cursor. getString (cursor. getColumnIndex ("username"); TV _phone.setText (cursor. getString (cursor. getColumnIndex ("userphone"); // Delete final int _ id = cursor Based on the id. getInt (cursor. getColumnIndex ("_ id"); final String name = cursor. getString (cursor. getColumnIndex ("username ") ); // Delete the registration event btn_del.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// Delete int count = contentResolver through the content parser. delete (Uri. parse ("content: //" + AUTHORITIE + "/delete"), "userid =? ", New String [] {_ id +" "}); if (count> 0) {Toast. makeText (MainActivity. this, "deleted successfully" + name, Toast. LENGTH_LONG ). show (); // reload initData () ;}} after deletion); // update final String age = cursor according to each entry. getString (cursor. getColumnIndex ("userage"); final String salary = cursor. getString (cursor. getColumnIndex ("usersalary"); final String phone = cursor. getString (cursor. getColumnIndex ("userphone"); // The registration event btn_upd.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Intent intent = new Intent (); intent. putExtra ("uid", _ id); intent. putExtra ("uname", name); intent. putExtra ("uage", age); intent. putExtra ("usalary", salary); intent. putExtra ("uphone", phone); intent. setClass (getApplicationContext (), UserUpdateActivity. class); startActivityForResult (intent, requestUpdCode );}});}}}


        Update UserUpdateActivity. java
        Package com. example. android_provider; import android. app. activity; import android. content. contentResolver; import android. content. contentValues; import android. content. intent; import android.net. uri; import android. OS. bundle; import android. view. view; import android. widget. editText; public class UserUpdateActivity extends Activity {// content parser private ContentResolver contentResolver; // operation flag private static final String AUTHORITIE = "www.csdn.com. provider. userContentProvider "; private EditText etName, etAge, etSalary, etId, etPhone; // result code private int resultCode = 2; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_user_update); findView (); // retrieves the Intent object intent = getIntent (); // you must add "" to the control to convert Intent values to numbers and convert them into etId strings. setText (intent. ge TIntExtra ("uid", 0) + ""); etName. setText (intent. getStringExtra ("uname"); etAge. setText (intent. getIntExtra ("uage", 18) + ""); etSalary. setText (intent. getDoubleExtra ("usalary", 0) + ""); etPhone. setText (intent. getStringExtra ("uphone"); // create the parser object contentResolver = getContentResolver ();} // search for the control public void findView () {etId = (EditText) findViewById (R. id. ed_upd_id); etName = (EditText) findViewById (R. id. ed _ Upd_name); etAge = (EditText) findViewById (R. id. ed_upd_age); etSalary = (EditText) findViewById (R. id. ed_upd_salary); etPhone = (EditText) findViewById (R. id. ed_upd_phone);} public void update (View v) {String uid = etId. getText (). toString (). trim (); String uname = etName. getText (). toString (). trim (); String uage = etAge. getText (). toString (). trim (); String usalart = etSalary. getText (). toString (). trim (); Strin G uphone = etPhone. getText (). toString (). trim (); // values. the key value of put (key, value) put must be the value ContentValues values = new ContentValues (); values. put ("userid", uid); values. put ("username", uname); values. put ("userage", uage); values. put ("usersalary", usalart); values. put ("userphone", uphone); int count = contentResolver. update (Uri. parse ("content: //" + AUTHORITIE + "/update"), values, "userid =? ", New String [] {uid}); Intent intent = new Intent (); intent. putExtra ("count", count); UserUpdateActivity. this. setResult (resultCode, intent); // close the resource this. finish ();}}


        Configuration File AndroidManifest. java
            
                
                                     
                                             
                          
                                         
            

        Knowledge Point Analysis Knowledge Point 1: LayoutInflater mInflater

        // Constructor public MyCursorAapter (Context context, Cursor c, int flags) {super (context, c, flags); this. context = context; mInflater = (LayoutInflater) context. getSystemService (Context. LAYOUT_INFLATER_SERVICE );}

        The role of mInflater as the pump, layout the service object

        The mInflater service returns a View control object through the inflate method.

        View objects converted from their layout files can be processed in bindView after conversion.

        First, the current layout is new, and each layout file is new.

        Knowledge Point 2: newView

        @Overridepublic View newView(Context context, Cursor cursor, ViewGroup parent) {return mInflater.inflate(R.layout.list_item_user, parent, false);}

        New: The current layout. You can use findViewById to get the control in bindView.


        Knowledge Point 3: cursor

        // Set the value TV _name.setText (cursor. getString (cursor. getColumnIndex ("username"); TV _phone.setText (cursor. getString (cursor. getColumnIndex ("userphone ")));

        Cursor. getColumnIndex (): column for cursor

        Cursor. getString (): value of the column corresponding to cursor


        Knowledge Point 4: startActivityForResult

        Use the startActivityForResult method if you have returned values when you disable the activity, and use the onActivityResult method to process the result again.

        @ Overrideprotected void onActivityResult (int requestCode, int resultCode, Intent data) {super. onActivityResult (requestCode, resultCode, data); // Request Code if (requestCode = requestUpdCode) {// result code if (resultCode = 2) {// if (data. getIntExtra ("count", 0)> 0) {initData (); // reload the Toast interface. makeText (this, "updated successfully", 0 ). show ();} else {Toast. makeText (this, "update failed", 0 ). show ();}}}}


        Knowledge Point 5: intent. getIntExtra (name, defaultValue)

        Set intent to the control. The values passed by intent must be converted into strings by adding "".

        // Obtain the Intent object intent = getIntent (); // set Intent for the control. The values passed by intent must be converted to the string etId by adding. setText (intent. getIntExtra ("uid", 0) + ""); etName. setText (intent. getStringExtra ("uname"); etAge. setText (intent. getIntExtra ("uage", 18) + ""); etSalary. setText (intent. getDoubleExtra ("usalary", 0) + ""); etPhone. setText (intent. getStringExtra ("uphone "));

        Knowledge Point 6: values. put (key, value)


        <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHByZSBjbGFzcz0 = "brush: java;"> ContentValues values = new ContentValues (); values. put ("userid", uid); values. put ("username", uname); values. put ("userage", uage); values. put ("usersalary", usalart); values. put ("userphone", uphone );

        The put key value must be the value in the database.


        Reprint please mark reprint address: http://blog.csdn.net/zhaoyazhi2129/article/details/29875555

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.