1. 程式人生 > >進階三:Android常用框架

進階三:Android常用框架

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)

String str="hello world";

//字串
ByteString byteString= ByteString.encodeUtf8(str);

//16進位制
String hex = byteString.hex();
ByteString byteString2=ByteString.decodeHex(hex);

//Base64編碼
String base64 = byteString.base64();
ByteString byteString3=ByteString.decodeBase64(base64);

//輸入輸出流
FileOutputStream outputStream=new FileOutputStream(file);
byteString3.write(outputStream);
FileInputStream inputStream=new FileInputStream(file);
ByteString byteString4=ByteString.read(inputStream,inputStream.available());

Buffer類

Source介面 輸入流

Sink介面 輸出流

okio.BufferedSource 介面 繼承自 source

okio.BufferedSink 介面 繼承自sink

okio.Buffer buffer=new okio.Buffer();

//讀寫字串
buffer.writeUtf8("hello world");
buffer.readUtf8(1);

//讀寫整數
buffer.writeInt(n);
buffer.readInt();

//輸入輸出流
buffer.readFrom(new FileInputStream("in.png"));
buffer.writeTo(new FileOutputStream("out.png");

//使用source和sink複製檔案,Okio是類
BufferedSource source = Okio.buffer(Okio.source(new File("in.txt")));//連結in.txt檔案
BufferedSink sink=Okio.buffer(Okio.sink(new File("out.txt")));//連結out.txt檔案
source.readAll(sink);//複製

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 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控制元件