Android基础_内容提供者(九)

内容提供者

首先创建数据库
public class DbOpenHelper extends SQLiteOpenHelper {

    public DbOpenHelper(Context context) {
        super(context, DbConst.DB_NAME, null//cursor是游标对象,置为空的就是表示是使用系统
                , DbConst.DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table "+DbConst.CONTACT_TABLE+"("+ DbConst._ID+" integer primary key autoincrement,"+DbConst._USERNAME+" text ,"+DbConst._PHONE+" text);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

public class MyContentProvider extends ContentProvider {
    /*创建一个内容提供者  唯一不需要intent的四大组件
     * 1.创建一个类并继承于ContentProvider
     * 2.注册 :provider > name authorities="包名"
     * 3.实现curd
     *      在contentprovider中有定义content方法 该context只能用于操作数据库,操作ui会报错
     *      getcontent();
     * */
    private DbOpenHelper mHelper;
    @Override
    public boolean onCreate() {
        mHelper = new DbOpenHelper(getContext());
        return false;
    }
    /* uri:统一资源定位符
     * projection 查询哪些字段
     * selection 查询条件
     * selectionArgs 查询条件绑定值
     * sortorder 排序
     * **/
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = mHelper.getReadableDatabase();
        return db.query(DbConst.CONTACT_TABLE, 
                projection, 
                selection, 
                selectionArgs, 
                null, 
                null, 
                null);
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }
    /*Uri 新的Uri 地址 传进去的包名 content://com.example.ReviewForDatabase/第几行
     * 1.将传进来的uri对象 转换成 String 
     *      uri.toString();
     * 2.将id返回到str的后面
     * 3.将str转换成uri
     * */
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = mHelper.getReadableDatabase();
        long id = db.insert(DbConst.CONTACT_TABLE, null, values);
        String  str = uri.toString();
        str=str+"/"+id;
        return Uri.parse(str);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

}

内容解析者

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    /* 1.获取内容解析者对象
     *      cr.query(uri, projection, selection, selectionArgs, sortOrder);
     *          1.uri
     *              Uri.parse(str);
     * */
    public void query(View v){
        ContentResolver cr = getContentResolver();
                Uri uri = Uri.parse("content://com.example.ReviewForDatabase/contact/1");
        String type = cr.getType(uri);
        Log.v("meeeeeee", ""+type);
        Cursor cursor = cr.query(uri, null, null, null, null);
        while (cursor.moveToNext()) {
            String username = cursor.getString(1);
            String phone = cursor.getString(2);
            Log.v("meeeeeee", ""+username +" "+phone);
        }
        cursor.close();
    }


    /* 1.获取内容解析者对象
     *  getContentResolver();
     * 2.cr.insert(uri,values)
     *      1.Uri.parse(content://包名)
     *      2.values  new ContentValues();
     *          values.put(key,value);
     * 3.第二步返回了一个uri ,uu;       
     * */
    public void insert(View v){
        ContentResolver cr = getContentResolver();
        Uri uri = Uri.parse("content://com.example.ReviewForDatabase");
        ContentValues value = new ContentValues();
        createData(value, "你妹","啊");
        Uri newuri = cr.insert(uri, value);
        Log.v("meeeeeee", " "+(newuri==null));
    }
    private void createData(ContentValues value,String str1,String str2) {
        value.put("phone", str2);
        value.put("username", str1);
    }


    public void delete(View v){
        ContentResolver cr = getContentResolver();
        Uri uri = Uri.parse("content://com.example.ReviewForDatabase/contact/1");
        int x = cr.delete(uri, null, null);
        Log.v("meeeeeee", "你猜删除了多少行...?   \n答案是"+x);
    }
    /*
     * 1.获取contentResolver 
     *      getContentResolver();
     * 2.cr.update(uri,value,null,null);
     *      1.Uri.parse(网址);
     *      2.new contentvalues ()
     *          contentvalue.put(key,value);
     * */
    public void modify(View v){
        ContentResolver cr = getContentResolver();

        Uri uri = Uri.parse("content://com.example.ReviewForDatabase/contact/1");

        ContentValues value = new ContentValues();
        value.put("username", "移动营业厅");
        value.put("phone", "10086");

        int raws = cr.update(uri, value, null, null);
        Log.v("meeeeeee", "修改了"+raws+"行");
    }
}

内容匹配者

public class MyContentProvider extends ContentProvider {
    /* 1.创建一个uri匹配对象
     *  new Urimatcher(code);
     *      
     * 2.规定合法uri
     * sUriMatcher.addURI(authority, path, code);
     *  1.autority:内容提供者的包名,
     *  2.path 传入的content://包名/  #代表数字  *任意字符
     *  3.匹配码
     * */
    private static final String AUTHORITY="com.example.ReviewForDatabase";
    private static UriMatcher sUriMatcher = new UriMatcher(0);
    static {
        sUriMatcher.addURI(AUTHORITY,"#",1);        
//      sUriMatcher.addURI(AUTHORITY,null,1);       
        sUriMatcher.addURI(AUTHORITY,"contact",2);      
        sUriMatcher.addURI(AUTHORITY,"contact/#",3);        
    }













    private DbOpenHelper mHelper;
//  官方规定该方法如果contentprovider创建成功的话,就返回true
    @Override
    public boolean onCreate() {
        mHelper = new DbOpenHelper(getContext());
        return false;
    }

    /* 用于返回一个类型供内容解析者判断是单行数据还是多行数据
     * mimeType   a(集合)/b(子集)
     * */
    @Override
    public String getType(Uri uri) {
        int code = sUriMatcher.match(uri);
        if (code==3) {
            return "vnd.android.cursor.item/contact";
        }else if (code==2) {
            return "vnd.android.cursor.dir/contacts";
        }
        return null;
    }





    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        int code = sUriMatcher.match(uri);
        Log.v("meeeeeee", "code="+code);
        if (code==1) {          
            SQLiteDatabase db = mHelper.getReadableDatabase();
            return db.query(DbConst.CONTACT_TABLE, 
                    projection, 
                    selection, 
                    selectionArgs, 
                    null, 
                    null, 
                    null);
        }else if (code==2) {
            SQLiteDatabase db = mHelper.getReadableDatabase();
            return db.query(DbConst.CONTACT_TABLE, 
                    null, 
                    null, 
                    null, 
                    null, 
                    null, 
                    null);
        }else if (code==3) {
            SQLiteDatabase db = mHelper.getReadableDatabase();
//          content://con.424.it.cp/contact/4
            List<String> pathSegments = uri.getPathSegments();
//          contact  4
            String id = pathSegments.get(pathSegments.size()-1);
//          4
            return db.query(DbConst.CONTACT_TABLE, null, DbConst._ID+"=?", new String[]{id}, null, null, null);
        }
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = mHelper.getReadableDatabase();
        int code = sUriMatcher.match(uri);
        Log.v("meeeeeee", "code="+code);
        long id = db.insert(DbConst.CONTACT_TABLE, null, values);
        String  str = uri.toString();
        str=str+"/"+id;
        return Uri.parse(str);
    }

//  db.delete(table, whereClause, whereArgs)    
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int code = sUriMatcher.match(uri);

        Log.v("meeeeeee", "code="+code);
        if (code==3) {
            List<String> pathsegments = uri.getPathSegments();
            String id = pathsegments.get(pathsegments.size()-1);
            SQLiteDatabase db = mHelper.getWritableDatabase();
            return db.delete(DbConst.CONTACT_TABLE, DbConst._ID+"=?", new String[]{id});
        }else if (code==2) {
            SQLiteDatabase db = mHelper.getWritableDatabase();
            return db.delete(DbConst.CONTACT_TABLE, null,null);         
        }
        return 0;
    }


    /*  修改的查询条件可以是uri的数字
     *如果是整张表 可以看有没有查询的条件
     *1.id判断
     *      1.获取需要修改的那一行
     *      
     *      2.修改某一行
     */
    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int code = sUriMatcher.match(uri);
        Log.v("meeeeeee", "code="+code);
        if (code==3) {
            List<String> pathsegments = uri.getPathSegments();
            String id = pathsegments.get(pathsegments.size()-1);
            Log.v("meeeeeee", "id="+id);
            SQLiteDatabase db = mHelper.getWritableDatabase();
            return db.update(DbConst.CONTACT_TABLE, values, DbConst._ID+"=?", new String[]{id});
        }else if (code==2) {
            SQLiteDatabase db = mHelper.getWritableDatabase();
            return db.update(DbConst.CONTACT_TABLE, values, null,null);

        }
        return 888;
    }

}

读取通话记录

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void get(View v){
        ContentResolver cr = getContentResolver();

        Uri uri = Uri.parse("content://包名/分类");

        Cursor cursor = cr.query(uri, null, null, null, null);
        while (cursor.moveToNext()) {
            String phone = cursor.getString(cursor.getColumnIndex("name"));
        }
    }
    public void insert(View v){
        ContentResolver cr = getContentResolver();
        Uri uri = Uri.parse("");
        ContentValues values = new ContentValues();
        values.put("key", "value");
        Uri curosr = cr.insert(uri, values);
    }
}

边界压缩

public class MainActivity extends Activity {
    ImageView mIv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mIv=(ImageView)findViewById(R.id.iv);
    }
    /* 等比例压缩一张图片
     * 1.拿到图片的宽高 计算出比例
     *      bmp.getwidth();
     *      bmp.getheigt();
     * 2.只获取宽高,不加载到内存中
     *      Options opts = new Options();
     *      opts.inJustDecodeBounds=true;
     * 3.获取屏幕的宽高
     *      WindowManager /getWindowManager();
     *      Display /manager.getDefaultDisplay();
     *      int/display.getWidth();
     *      int/displayHeight=display.getHeight();
     * 4.计算宽高比例
     * 5.进行等比例压缩
     * */
    public void readPic(View v){
        File file = new File (getFilesDir(),"largeimage.jpg");

        Options opts = new Options();

        opts.inJustDecodeBounds=true;

        WindowManager manager = getWindowManager();
        Display display = manager.getDefaultDisplay();
        Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath(),opts);
        int sWidth = display.getWidth();
        int sHeigh = display.getHeight();

        float widthScale = opts.outWidth/sWidth*1.0f;
        float heightScale = opts.outHeight/sHeigh*1.0f;
        float realScale = 1;
        if (widthScale>heightScale&&widthScale>1) {
            realScale=widthScale;
        }
        if (heightScale>widthScale&&heightScale>1) {
            realScale=heightScale;
        }

        opts.inSampleSize=(int)realScale;

        opts.inJustDecodeBounds=false;
        Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath(),opts);
        Log.v("meeeeeee", bm.getWidth()+" "+ bm.getHeight());
        Log.v("meeeeeee", "比例"+realScale);

        mIv.setImageBitmap(bm);
    }
}

声音池的使用

public class MainActivity extends Activity {
    /* 在oncreate把要使用的声音一次性加载到池子中
     * 1.new SoundPool(maxStream,streamType,srcQuality);
     *      1.maxStream 最大存储数量
     *      2.声音类型
     *      3.
     * 2.将声音文件添加进声音池.
     *  mSoundPool.load();
     * 3.播放 mSoundPool.play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate/声音频率);
     * */
    int mSoundId;
    private SoundPool mSoundPool;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSoundPool=new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        mSoundId = mSoundPool.load(this, R.raw.alarm, 1);
    }
    public void play(View v){
        mSoundPool.play(mSoundId, 1.0f, 1.0f, 5, 0, 1.0f);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值