Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 趙雅智_android通過內容提供者實現電話薄顯示更新刪除案例

趙雅智_android通過內容提供者實現電話薄顯示更新刪除案例

編輯:關於Android編程

需求分析:

通過ContentResolver操作內容提供者的數據,將姓名,電話顯示在listView中,並帶有添加和刪除按鈕進行相應操作

實現思路步驟:

    Adater模型層 創建內容解析器對象 ContentResolver定義URI 自定義CursorAdapter 實現構造器public MyCursorAapter(Context context, Cursor c, int flags)實現public View newView(Context context, Cursor cursor, ViewGroup parent)方法實現public void bindView(View view, Context context, Cursor cursor)
      給adapter設置顯示數據 查找控件給控件設置值 刪除數據
        contentResolver的delete方法刪除數據
        重新初始化數據 更新數據 新建activity和布局文件在MainActivity中通過intent跳轉activity並將點擊對應位置的值傳到更新界面 獲取相對應的數據通過intent跳轉activity用startActivityForResult發送帶有數據的返回值 查找控件並賦值 查找控件將intent傳過來的值賦給控件 創建內容解析器通過內容解析器更新數據 uri聲明通過ContentValues放值 將結果碼和更新結果值傳回MainActivity在MainActivity中重寫onActivityResult方法處理更新成功或者失敗 用內容解析器初始化數據並設置adapter contentResolver的query方法查找數據
        在視圖中綁定

        實現效果

        主界面 \
        刪除bbb \
        點擊更新後打開的界面 \

        更新數據 \

        更新後界面 \

        主要代碼

        contentprovider共享的數據和ContentProvider介紹一樣 http://blog.csdn.net/zhaoyazhi2129/article/details/29839561

        布局文件

        activity_main.xml
        
        
            
             
            
        
        

        list_item_user.xml
        
        
        
            
        activity_user_update.xml
        
        
            
        
                
        
                
            
        
            
        
                
        
                
        
                    
                
            
        
            
        
                
        
                
        
                    
                
            
        
            
        
                
        
                
        
                    
                
            
        
            
        
                
        
                
        
                    
                
            
        
            
        
             
                

        主程序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.view.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;
        	// 內容解析器
        	private ContentResolver contentResolver;
        	// 操作的標志
        	private static final String AUTHORITIE = "www.csdn.com.provider.userContentProvider";
        	// 請求碼
        	int requestUpdCode = 1;
        
        	@Override
        	protected void onCreate(Bundle savedInstanceState) {
        		super.onCreate(savedInstanceState);
        		setContentView(R.layout.activity_main);
        		// 模型層
        		// 創建內容解析器對象
        		contentResolver = getContentResolver();
        		lv_user = (ListView) findViewById(R.id.listView1);
        		initData();
        	}
        
        	/**
        	 * 查找數據
        	 */
        	private void initData() {
        		// 控制層(自定義)
        		Cursor c = contentResolver.query(
        				Uri.parse("content://" + AUTHORITIE + "/query"), new String[] {
        						"userid as _id", "username", "userage", "usersalary",
        						"userphone" }, null, null, null);
        		MyCursorAapter adapter = new MyCursorAapter(this, c,
        				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        		// 視圖層
        		lv_user.setAdapter(adapter);
        	}
        
        	@Override
        	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        		super.onActivityResult(requestCode, resultCode, data);
        		// 請求碼
        		if (requestCode == requestUpdCode) {
        			// 結果碼
        			if (resultCode == 2) {
        				// 傳過來的數據
        				if (data.getIntExtra("count", 0) > 0) {
        					initData();// 重新加載界面
        					Toast.makeText(this, "更新成功", 0).show();
        				} else {
        					Toast.makeText(this, "更新失敗", 0).show();
        				}
        
        			}
        		}
        	}
        
        	class MyCursorAapter extends CursorAdapter {
        		// 上下文對象
        		private Context context;
        		// 打氣筒,布局服務對象
        		private LayoutInflater mInflater;
        
        		// 構造器
        		public MyCursorAapter(Context context, Cursor c, int flags) {
        			super(context, c, flags);
        			this.context = context;
        			mInflater = (LayoutInflater) context
        					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        		}
        
        		// mInflater服務通過inflate方法返回一個View控件對象
        		// 通過自己的布局文件轉化的View對象,轉化之後就可以在bindView處理
        		// 先new出當前的布局。new出每一個條目的布局文件。
        		// new出當前布局,bindView中就可以用findViewById去拿控件
        		@Override
        		public View newView(Context context, Cursor cursor, ViewGroup parent) {
        
        			return mInflater.inflate(R.layout.list_item_user, parent, false);
        		}
        
        		@Override
        		public void bindView(View view, Context context, Cursor cursor) {
        			// 查找組件
        			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);
        
        			// 設置值
        			tv_name.setText(cursor.getString(cursor.getColumnIndex("username")));
        			tv_phone.setText(cursor.getString(cursor
        					.getColumnIndex("userphone")));
        
        			// 根據id刪除
        			final int _id = cursor.getInt(cursor.getColumnIndex("_id"));
        			final String name = cursor.getString(cursor
        					.getColumnIndex("username"));
        
        			// 刪除按鈕的注冊事件
        			btn_del.setOnClickListener(new OnClickListener() {
        
        				@Override
        				public void onClick(View v) {
        					// 通過內容解析器刪除
        					int count = contentResolver.delete(
        							Uri.parse("content://" + AUTHORITIE + "/delete"),
        							"userid=?", new String[] { _id + "" });
        
        					if (count > 0) {
        						Toast.makeText(MainActivity.this, "成功刪除掉" + name,
        								Toast.LENGTH_LONG).show();
        						// 刪除後重新加載
        						initData();
        					}
        				}
        			});
        			// 根據每條更新
        			final String age = cursor.getString(cursor
        					.getColumnIndex("userage"));
        			final String salary = cursor.getString(cursor
        					.getColumnIndex("usersalary"));
        			final String phone = cursor.getString(cursor
        					.getColumnIndex("userphone"));
        			// 更新按鈕的注冊事件
        			btn_upd.setOnClickListener(new OnClickListener() {
        
        				@Override
        				public 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);
        
        				}
        			});
        		}
        	}
        
        }
        


        更新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 {
        	// 內容解析器
        	private ContentResolver contentResolver;
        	// 操作的標志
        	private static final String AUTHORITIE = "www.csdn.com.provider.userContentProvider";
        
        	private EditText etName, etAge, etSalary, etId, etPhone;
        	// 結果碼
        	private int resultCode = 2;
        
        	@Override
        	protected void onCreate(Bundle savedInstanceState) {
        		super.onCreate(savedInstanceState);
        		setContentView(R.layout.activity_user_update);
        
        		findView();
        		// 獲取意圖對象
        		Intent intent = getIntent();
        		// 給控件設置intent傳過來的值 是數字都必須加“”轉為字符串
        		etId.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"));
        
        		// 創建解析器對象
        		contentResolver = getContentResolver();
        	}
        
        	// 查找控件
        	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();
        		String uphone = etPhone.getText().toString().trim();
        
        		// values.put(key, value)put的key值必須是數據庫裡的值
        		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);
        		// 關閉資源
        		this.finish();
        	}
        }
        


        配置文件AndroidManifest.java

        
        
        
            
        
            
                
                    
                        
        
                        
                    
                
                
                
            
        
        
        

        知識點解析

        知識點1:LayoutInflater mInflater

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

        mInflater充當打氣筒的角色,布局服務對象

        mInflater服務通過inflate方法返回一個View控件對象

        通過自己的布局文件轉化的View對象,轉化之後就可以在bindView處理

        先new出當前的布局,new出每一個條目的布局文件。

        知識點2:newView

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

        new出當前布局,bindView中就可以用findViewById去拿控件


        知識點3:cursor

        //設置值
        			tv_name.setText(cursor.getString(cursor.getColumnIndex("username")));
        			tv_phone.setText(cursor.getString(cursor
        					.getColumnIndex("userphone")));

        cursor.getColumnIndex():cursor對於的列

        cursor.getString():cursor對應列的值


        知識點4:startActivityForResult

        當你關閉activity時有返回值的情況下用startActivityForResult方法,並通過重新onActivityResult方法處理

        	@Override
        	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        		super.onActivityResult(requestCode, resultCode, data);
        		// 請求碼
        		if (requestCode == requestUpdCode) {
        			// 結果碼
        			if (resultCode == 2) {
        				// 傳過來的數據
        				if (data.getIntExtra("count", 0) > 0) {
        					initData();// 重新加載界面
        					Toast.makeText(this, "更新成功", 0).show();
        				} else {
        					Toast.makeText(this, "更新失敗", 0).show();
        				}
        
        			}
        		}
        	}


        知識點5:intent.getIntExtra(name, defaultValue)

        給控件設置intent傳過來的值 是數字都必須加“”轉為字符串

        		// 獲取意圖對象
        		Intent intent = getIntent();
        		// 給控件設置intent傳過來的值 是數字都必須加“”轉為字符串
        		etId.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"));

        知識點6:values.put(key, value)

        \

        <喎?/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);

        put的key值必須是數據庫裡的值


        轉載請標明轉載地址:http://blog.csdn.net/zhaoyazhi2129/article/details/29875555

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved