Android网络操作与数据存储(三):Android常用框架

目录

OrmLite数据库框架

常用ORM框架有:

下载OrmLite开发包

导入工程

使用

1、创建实体类,添加注解

2、创建帮助类,继承OrmLiteSqliteOpenHelper

3、获得对应表的Dao类

4、执行增删改查操作

一对多关系

事务

Okio框架

导包

常用类

ByteString类

Buffer类

OkHttp框架

导包

使用

picasso框架

一、Picasso类

二、RequestCreator类

三、Transformation接口 ,图像类型转换


OrmLite数据库框架

常用ORM框架有:

--OrmLite 使用注解,使用简单

--GreenDAO 自动生成代码,性能高

--SugarORM

--Active Android

--Realm

下载OrmLite开发包

http://ormlite.com 下载ormlite-android-x.xx.jar和ormlite-core-x.xx.jar

导入工程

复制到libs,选中->右键->Add As Library

使用

1、创建实体类,添加注解

表前添加

@DatabaseTable[tableName="tb_student"]

字段前添加

@DatabaseField(generatedId=true)

@DatabaseField(columnName="name",dataType=DataType.STRING,canBeNull=false]

@DatabaseField

2、创建帮助类,继承OrmLiteSqliteOpenHelper

实现单例模式:

public static synchronized DatabaseHelper getInstance(Context context){

    if(sInstance==null){

        sInstance=new DatabaseHelper(context);

    }

    return sInstance;

}

onCreate方法:

TableUtils.createTable(connectionSource,Student.class);//Student为带注解的实体类名

onUpgrade方法:

TableUtils.dropTable(connectionSrouce,Student.class,true);//true 忽略错误

onCreate(sqlLiteDatabase,connectionSrouce);//调用onCreate方法重新创建表

3、获得对应表的Dao类

DatabaseHelper helper=DatabaseHelper.getInstance(this);//获得DatabaseHelper实例

Dao<Student,Ingteger> stuDao=helper.getDao(Student.class);//获得表的DAO,泛型:类型、编号

4、执行增删改查操作

插入数据:

Student stu1=new Student("张三",33,"13300001111");

Student stu2=new Student("李四",23,"13300002222");

Student stu3=new Student("王五,21,"13300003333");

stuDao.create(stu1);

stuDao.createOrUpdate(stu2);

stuDao.createIfNoExists(stu3);

查询数据:

List<Student> students1=stuDao.queryForAll();

List<Student> students2=stuDao.queryForId(3);

List<Student> students3=stuDao.queryForEq("name","李四");

更新数据:

UpdateBuilder update=stuDao.updateBuilder();

update.setWhere(update.where().eq("phone","13300002222").and().gt("age",20));//gt:大于,lt:小于

update.updateColumnValue("name","小李子");

update.updateColumnValue("phone","13899998888");

update.update();

stuDao.updateRaw("update tb_student set name='小张',phone='13844448888' where id=?","1");

删除数据:

stuDao.deleteById(1);

一对多关系

Student类

...

@DatabaseField(column="school_id",foreign=true,foreignAutoRefresh=true)

private School school;

School类

...

@ForeignCollectionField

private Collection<Student> students;

事务

批量数据操作时,大大提高操作效率。事务是一个整体,要么全执行,要么全不执行。

如果把1000条数据放到一个事务里插入数据库中。将一次性插入;一条出错整体不能插入。

DatabaseHelper helper=DatabaseHelper.getInstance(this);

final Dao<Student,Integer> stuDao=helper.getDao(Student.class);

final Student stu=new Student("测试事务",18,"110",new Shool("清华大学","北京"));

TransactionManager.callInTransaction(

            helper.getConnectionSource(),

            new Callable<Void>(){

                @Override

                public Void call() throws Exception{

                    for(int i=0;i<20;i++){
                        stuDao.create(stu);
                        if(i==10){
                            throw new SQLException("test");
                        }
                    }
                    return null;
                }
            });

 

Okio框架

导包

module,右键->Open module settings ->dependencies->添加,搜索"okio",选择com.squareup.okio:okio:x.x.x

常用类

ByteString类

创建

okio.ByteString#of(byte...) 输入字节,输出ByteString对象

okio.ByteString#encodeUtf8 输入字符串,输出ByteString对象

okio.ByteString#decodeHex 输入16进制串,输出ByteString对象

okio.ByteString#decodeBase64 输入Base64编码,输出ByteString对象

okio.ByteString#read 输入InputStream,输出ByteString对象

方法

okio.ByteString#base64 返回base64字符串

okio.ByteString#hex 返回16进制的字符串

okio.ByteString#md5 返回字节串的md5值

okio.ByteString#sha1

okio.ByteString#write(java.io.OutputStream)

@RunWith(AndroidJUnit4.class)
public class OkioTest {
    private static final String TAG = "OkioTest";
    @Test
    public void testByteString() throws IOException {
        String str="hello world!";
        Log.d(TAG, "testOkio: "+str);

        //字符串
        ByteString byteString = ByteString.encodeUtf8(str);
        Log.d(TAG, "字符串: "+byteString);

        //16进制
        String hex = byteString.hex();
        Log.d(TAG, "16进制: "+hex);
        ByteString byteString1 = ByteString.decodeHex(hex);
        Log.d(TAG, "10进制: "+byteString1);

        //Base64编码
        String s = byteString.base64();
        Log.d(TAG, "Base64: "+s);
        ByteString byteString2 = ByteString.decodeBase64(s);
        Log.d(TAG, "Base64解码: "+byteString2);

        //MD5值
        ByteString byteString3 = byteString.md5();
        Log.d(TAG, "md5值: "+byteString3.hex());

        //sha1值
        String hex1 = byteString.sha1().hex();
        Log.d(TAG, "sha1值: "+hex1);

        //输入输出流
        Context context = InstrumentationRegistry.getTargetContext();
        File filesDir = context.getFilesDir();
        File file=new File(filesDir,"haha.txt");
        FileOutputStream outputStream=new FileOutputStream(file);
        byteString.write(outputStream);

        FileInputStream inputStream=new FileInputStream(file);
        ByteString read = ByteString.read(inputStream, inputStream.available());
        Log.d(TAG, "读取输入流: "+read);

        outputStream.close();
        inputStream.close();
    }
}

Buffer类

Source接口 输入流(相当于InputStream)

  • read(sink: Buffer, byteCount: Long)//从数据源读取数据
  • timeout()//超时
  • close()//关闭数据源

Sink接口 输出流(相当于OutStream)

  • write(source: Buffer, byteCount: Long)//向数据接收方写数据
  • flush()
  • timeout()//超时
  • close()//关闭数据源

okio.BufferedSource 接口 继承自 source

okio.BufferedSink 接口 继承自sink

Buffer类 实现BufferedSource, BufferedSink两个接口。Buffer的内部实现是一个ArrayList。

@RunWith(AndroidJUnit4.class)
public class OkioTest {
    @Test
    public void testBuffer() throws IOException {
        Buffer buffer = new Buffer();
        System.out.println(buffer);

        //字符串
        buffer.writeUtf8("abc");
        while(!buffer.exhausted()){
            Log.d(TAG, "testBuffer: "+buffer.readUtf8(1));
        }

        //整型
        for (int i = 0; i < 10; i++) {
            buffer.writeInt(i);
        }
        while(!buffer.exhausted()){
            Log.d(TAG, "testBuffer: "+buffer.readInt());
        }

        //输入输出流
        Context context = InstrumentationRegistry.getTargetContext();
        InputStream inputStream = context.getResources().openRawResource(R.drawable.img01);

        File filesDir = context.getFilesDir();
        File file=new File(filesDir,"out.jpg");
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream outputStream=new FileOutputStream(file);

        buffer.readFrom(inputStream);
        buffer.writeTo(outputStream);

        inputStream.close();
        outputStream.close();

        //source、sink
        File path = context.getFilesDir();
        File sourceFile=new File(path,"out.jpg");
        Source source = Okio.source(sourceFile);//创建Source,参数可以是文件、接口、流、路径
        BufferedSource bufferedSource = Okio.buffer(source);//创建BufferedSource

        File sinkFile=new File(path,"sink.jpg");
        if(!sinkFile.exists()){
            sinkFile.createNewFile();
        }
        Sink sink = Okio.sink(sinkFile);//创建Sink
        BufferedSink bufferedSink = Okio.buffer(sink);//创建BufferedSink

        //复制文件
        bufferedSource.readAll(bufferedSink);
        
        bufferedSource.close();
        bufferedSink.close();
        source.close();//需要关闭?
        sink.close();//需要关闭?

    }
}

OkHttp框架

导包

module,右键->Open module settings ->dependencies->添加,搜索"okhttp",选择com.squareup.okhttp3:okhttp:x.x.x

使用

public class MainActivity extends AppCompatActivity {

    public static final String POST_URL = "https://api.github.com/markdown/raw";
    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
    private final OkHttpClient mClient= new OkHttpClient();
    private static final String TAG = "MainActivity-xx";
    private TextView mTvContent;

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

        mTvContent = findViewById(R.id.content_tv);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.actions,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_get:
                get();
            break;
            case R.id.menu_response:
                response();
                break;
            case R.id.menu_post:
                post();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void post() {
        Request.Builder builder = new Request.Builder();
        builder.url(POST_URL);
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_MARKDOWN,
                "Hello world github/linguist#1 **cool**,and #1!");
        builder.post(requestBody);
        Request request = builder.build();
        Call call = mClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String content = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTvContent.setText(content);
                        }
                    });
                }
            }
        });
    }

    private void response() {
        Request.Builder builder=new Request.Builder();
        builder.url("https://raw.githubusercontent.com/square/okhttp/master/README.md");
        Request build = builder.build();

        Call call = mClient.newCall(build);

        //异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure() called with: call = [" + call + "], e = [" + e + "]");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse() called with: call = [" + call + "], response = [" + response + "]");
                if (response.isSuccessful()) {
                    //Response对象包含Code、Headers、body 三部分
                    int code = response.code();
                    Headers headers = response.headers();//map格式
                    String contentType = headers.get("Content-Type");//获取header内部信息
                    String string = response.body().string();
                    final StringBuilder stringBuilder=new StringBuilder();
                    stringBuilder.append("code:"+code);
                    stringBuilder.append("\n<---分割线--->\nheaders:"+headers);
                    stringBuilder.append("\n<---分割线--->\nBody:"+string);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTvContent.setText(stringBuilder);
                        }
                    });
                }
            }
        });
    }

    private void get() {
        //线程池
        ExecutorService executor= Executors.newSingleThreadExecutor();
        executor.submit(new Runnable() {
            @Override
            public void run() {
                //创建Request对象
                Request.Builder builder = new Request.Builder();
                builder.url("https://raw.githubusercontent.com/square/okhttp/master/README.md");
                Request request = builder.build();
                Log.d(TAG, "run: "+request);

                //创建Call对象
                Call call = mClient.newCall(request);
                try {
                    //同步请求,创建Response对象
                    Response response = call.execute();
                    Log.d(TAG, "run: "+response);
                    //处理数据
                    if (response.isSuccessful()) {
                        final String string = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTvContent.setText(string);
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        executor.shutdown();
    }
}

picasso框架

强大的图片下载、类型转换以及缓存管理框架

官网:http://square.github.io/picasso

一、Picasso类

0、public static Picasso get() 获取Picasso类

1、public RequestCreator load(@Nullable String path)根据指定路径加载图片资源

2、public void setIndicatorsEnabled(boolean enabled)是否显示调试的图像

  • 红色:代表网络下载的图片
  • 黄色:代表磁盘缓冲中加载的图片
  • 绿色:代表内存中加载的图片

二、RequestCreator类

1、public void into(ImageView target)将加载图片自适应到ImageView控件

2、public RequestCreator rotate(float degrees)对图片进行旋转

3、public RequestCreator centerCrop()对图像进行剪裁

4、public RequestCreator resize(int targetWidth, int targetHeight)重新定义图片大小

5、public RequestCreator placeholder(int placeholderResId或Drawable placeholderDrawable)设置图片加载时的占位符

6、public RequestCreator error(int errorResId或Drawable errorDrawable)图片无法加载时用参数中的图片显示

三、Transformation接口 ,图像类型转换

//类型转换
    class DefineTransformation implements Transformation {

        @Override
        public Bitmap transform(Bitmap source) {
            int size = Math.min(source.getWidth(), source.getHeight());
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;
            Bitmap result = Bitmap.createBitmap(source, x, y, size / 2, size / 2);
            if (result != source) {
                source.recycle();
            }
            return result;
        }

        @Override
        public String key() {
            return "icon";
        }
    }

 

//使用下载:自动缓存的磁盘内存或者内存缓存

Picasso picasso=Picasso.with(MainActivity.this)
.load(mDataUris.get(arg0))//mDataUris.get(arg0)是图片地址
.setIndicatorsEnabled(true)//设置调试模式
.resize(100,100)//设置图像大小
.centerCrop//剪切长或宽填充
.rotate(90)//旋转90度
.placeholder(R.drawable.ic_launcher)//占位符
.error(R.drawable.ic_launcher)//图片加载失败是显示的图片
into(icon)//icon是一个ImageView控件
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值