导入依赖
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
get异步:
①创建OKhttpclient对象 new OkHttpClient.Builder().build();
②构建请求对象 new Request.Builder().get().url(url).build();
③获取call对象 okHttpClient.newCall(request);
④call执行请求 call.enqueue(new Callback() {}
private void getEn() {
//创建okhttpClient 对象
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new caCheInterCeptor())
.addNetworkInterceptor(new caCheInterCeptor())
.cache(new Cache(getCacheDir(), 1024 * 1024 * 60))
.build();
//构建请求对象
Request request = new Request.Builder()
.url(foodUrl + paramse + page)
.get()
.build();
//获取call对象
Call call = okHttpClient.newCall(request);
//call执行请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("TAG", "onResponse当前线程:" + Thread.currentThread().getName());
String json = response.body().string();
Log.i("TAG", "json" + json.toString());
Gson gson = new Gson();
final FoodBean foodBean = gson.fromJson(json, FoodBean.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
btn_get_en.setText(foodBean.getData().get(5).getTitle());
}
});
}
});
post异步:
①创建OKhttpclient 对象new OkHttpClient.Builder().build();
②创建请求体 new FormBody.Builder().add(“stage_id”, “1”).build();
③构建请求对象 new Request.Builder().url(url+from).post(body).build();
④获取call对象 okHttpClient.newCall(request);
⑤call执行请求 call.enqueue(new Callback() {}
private void postEn() {
//创建 okhttpClient 对象
OkHttpClient okHttpClient = new OkHttpClient.Builder()
//超时设置
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
// .addInterceptor(new LogginInterCeptor())//应用拦截器
// .addNetworkInterceptor(new LogginInterCeptor())//网络拦截器
//缓存设置
.cache(new Cache(new File(getCacheDir(), "cache"), 10 * 1024 * 1024))
.build();
//创建请求体
FormBody body = new FormBody.Builder()
//表单提交
.add("stage_id", "1")
.add("limit", "20")
.add("page", "1")
.build();
//创建请求对象
Request request = new Request.Builder()
//请求头设置
.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.header("User-Agent", "gaoxiaoqianliutao")
.url(foodUrl + paramse + page)
.post(body)
.build();
//获取call对象
Call call = okHttpClient.newCall(request);
//call执行请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//响应行
Log.i("ok", "响应行protocol=" + response.protocol() + "code=" + response.code() + "message=" + response.message());
//响应头
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
Log.i("ok", headers.name(i) + ":" + headers.value(i));
}
//响应体
String json = response.body().string();
final FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
btn_post_en.setText(foodBean.getData().get(5).getTitle());
}
});
}
});
}
请求体
1.form:FormBody.builder().build();
private void postFrom() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
FormBody body = new FormBody.Builder()
.add("page", "1")
.add("limit", "20")
.add("stage_id", "1")
.build();
Request request = new Request.Builder()
.url(foodUrl + parame)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:"+e
.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
Log.i("TAG", foodBean.getData().get(2).getTitle());
}
});
}
2.string:RequestBody.create(type,"");
private void postString() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
MediaType mediaType = MediaType.parse(formType);
String content="stage_id=1&limit=20&page=1";
RequestBody requestBody = RequestBody.create(mediaType, content);
Request request = new Request.Builder()
.url(foodUrl + parame)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:"+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
Log.i("TAG", foodBean.getData().get(4).getTitle());
}
});
}
3.json
private void postJson() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
FoodJsonBean foodJsonBean = new FoodJsonBean();
foodJsonBean.setLimit("20");
foodJsonBean.setPage("1");
foodJsonBean.setStage_id("1");
Gson gson = new Gson();
String json = gson.toJson(foodJsonBean);
MediaType mediaType = MediaType.parse(jsonType);
RequestBody requestBody = RequestBody.create(mediaType, json);
Request request = new Request.Builder()
.url(foodUrl + parame)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:"+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
Log.i("TAG", foodBean.getData().get(8).getTitle());
}
});
}
4.stream:new RequestBody()
private void postSteam() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse(formType);
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(steamType);
}
};
Request request = new Request.Builder()
.url(foodUrl + parame)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "网络错误:"+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
Log.i("TAG", foodBean.getData().get(6).getTitle());
}
});
}
5.file
请求头、缓存、超时
请求头:reques.header() request.addHeader()
缓存:okHttpClient.cacha(new Cache(file,time))
超时:ok.timeout()
retrofit依赖
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
数据解析器依赖(工厂) (直接可以response.body(),不用new Gson了,非常的方便)
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
retrofit使用步骤
①创建接口服务类:baseURL和方法
②创建retrofit对象 new Retrofit.Builder().baseUrl"(“ApiService.baseUrl”).build();
③通过retrofit对象获取接口服务对象 retrofit.create(ApiService.class);
④接口服务对象调用自己的方法 apiService.get();
⑤通过call执行请求 call.enqueue(new Callback() {}
下面是12种常用注解!!!
每个都要有一个baseUrl呦!!!
//baseUrl必须以 "/" 结尾
String baseUrl="http://www.qubaobei.com/ios/cf/";
@GET("dish_list.php?stage_id=1&limit=20&page=1")
Call<ResponseBody> get1();
private void get1() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiServer.baseUrl)
.build();
//获取接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//接口服务对象调用接口中的方法得到call对象
Call<ResponseBody> call = apiServer.get1();
//call执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//当前线程
Log.i("TAG", "当前线程" + Thread.currentThread().getName());
try {
String json = response.body().string();
Log.i("TAG", "responseBody:" + json);
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
btn_get1.setText(foodBean.getData().get(3).getTitle());
Toast.makeText(MainActivity.this, foodBean.getData().get(5).getTitle(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
@GET("dish_list.php?")
Call<ResponseBody> get2(@Query("stage_id")String stage_id,@Query("limit")String limit,@Query("page")String page);
private void get2() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiServer.baseUrl)
.build();
//获取接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//接口服务对象调用接口中的方法得到call
Call<ResponseBody> call = apiServer.get2("1", "20", "1");
//call执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
btn_get2.setText(foodBean.getData().get(3).getTitle());
Toast.makeText(MainActivity.this, foodBean.getData().get(4).getTitle(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
@GET("dish_list.php?")
Call<ResponseBody> get3(@QueryMap Map<String,String>map);
private void get3() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiServer.baseUrl).build();
//获取接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//接口服务对象调用接口中的方法得到call
HashMap<String, String> map = new HashMap<>();
map.put("stage_id", "1");
map.put("limit", "20");
map.put("page", "1");
Call<ResponseBody> call = apiServer.get3(map);
//call执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
btn_get3.setText(foodBean.getData().get(8).getTitle());
Toast.makeText(MainActivity.this, foodBean.getData().get(0).getTitle(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
@GET("dish_list.php?stage_id=1&limit=20&page=1")
Call<FoodBean> getCon();
private void getCon() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiServer.baseUrl)
.build();
//获取接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//接口服务对象调用接口里的方法得到call
Call<FoodBean> call = apiServer.getCon();
//call执行请求
call.enqueue(new Callback<FoodBean>() {
@Override
public void onResponse(Call<FoodBean> call, Response<FoodBean> response) {
FoodBean foodBean = response.body();
btn_con.setText(foodBean.getData().get(2).getTitle());
}
@Override
public void onFailure(Call<FoodBean> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
@GET
Call<FoodBean> get4(@Url()String url);
private void get4() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiServer.baseUrl)
.build();
//获取接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//接口服务对象调用接口里的方法得到call
Call<FoodBean> call = apiServer.get4("dish_list.php?stage_id=1&limit=20&page=1");
//call执行请求
call.enqueue(new Callback<FoodBean>() {
@Override
public void onResponse(Call<FoodBean> call, Response<FoodBean> response) {
FoodBean foodBean = response.body();
btn_get4.setText(foodBean.getData().get(2).getTitle());
}
@Override
public void onFailure(Call<FoodBean> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
@GET
Call<FoodBean> get5(@Url()String url,@Query("stage_id")String stage_id,@Query("limit")String limit,@Query("page")String page);
private void get5() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiServer.baseUrl)
.build();
//获取接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//接口服务对象调用接口里的方法得到call
Call<FoodBean> call = apiServer.get5("dish_list.php?", "1", "20", "1");
//call执行请求
call.enqueue(new Callback<FoodBean>() {
@Override
public void onResponse(Call<FoodBean> call, Response<FoodBean> response) {
FoodBean foodBean = response.body();
btn_get5.setText(foodBean.getData().get(5).getTitle());
}
@Override
public void onFailure(Call<FoodBean> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
@GET("{dish_list}.php?stage_id=1&limit=20&page=1")
Call<FoodBean> get6(@Path("dish_list")String dish_list);
private void get6() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiServer.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiServer apiServer = retrofit.create(ApiServer.class);
Call<FoodBean> call = apiServer.get6("dish_list");
call.enqueue(new Callback<FoodBean>() {
@Override
public void onResponse(Call<FoodBean> call, Response<FoodBean> response) {
FoodBean foodBean = response.body();
btn_get6.setText(foodBean.getData().get(6).getTitle());
}
@Override
public void onFailure(Call<FoodBean> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
@POST("dish_list.php?")
@FormUrlEncoded
Call<ResponseBody> post1(@Field("stage_id") String stage_id, @Field("limit") String limit, @Field("page") String page);
private void post1() {
//retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiServer.baseUrl)
.build();
//接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//获取call
Call<ResponseBody> call = apiServer.post1("1", "20", "1");
//call执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
btn_post1.setText(foodBean.getData().get(0).getTitle());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("TAG", "网络错误:" + t.getMessage());
}
});
}
@POST("dish_list.php?")
@FormUrlEncoded
Call<ResponseBody> post2(@FieldMap Map<String,String> map);
private void post2() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiServer.baseUrl).build();
//获取接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//接口服务对象调用接口中的方法得到call
HashMap<String, String> map = new HashMap<>();
map.put("stage_id", "1");
map.put("limit", "20");
map.put("page", "1");
Call<ResponseBody> call = apiServer.post2(map);
//call执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
btn_post2.setText(foodBean.getData().get(0).getTitle());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
@POST("dish_list.php?")
@Headers("Content-Type:application/x-www-form-urlencoded")
Call<ResponseBody> post3(@Body RequestBody requestBody);
private void post3() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiServer.baseUrl).build();
//获取接口服务对象
ApiServer apiServer = retrofit.create(ApiServer.class);
//接口服务对象调用接口中的方法得到call
FormBody formBody = new FormBody.Builder()
.add("stage_id", "1")
.add("limit", "20")
.add("page", "1")
.build();
Call<ResponseBody> call = apiServer.post3(formBody);
//call执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
btn_post3.setText(foodBean.getData().get(0).getTitle());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
@POST("dish_list.php?")
@Headers("Content-Type:application/json")
Call<ResponseBody> post4(@Body RequestBody requestBody);
private void post4() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiServer.baseUrl).build();
ApiServer apiServer = retrofit.create(ApiServer.class);
FoodJsonBean foodJsonBean = new FoodJsonBean();
foodJsonBean.setLimit("20");
foodJsonBean.setStage_id("1");
foodJsonBean.setPage("1");
Gson gson = new Gson();
String json = gson.toJson(foodJsonBean);
RequestBody body = RequestBody.create(MediaType.parse("Content-Type:application/json"), json);
Call<ResponseBody> call = apiServer.post4(body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
btn_post4.setText(foodBean.getData().get(0).getTitle());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
@POST
Call<ResponseBody> post5(@Url() String url, @Body RequestBody requestBody,@Header("Content-Type")String type );
private void post5() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiServer.baseUrl).build();
ApiServer apiServer = retrofit.create(ApiServer.class);
FoodJsonBean foodJsonBean = new FoodJsonBean();
foodJsonBean.setLimit("20");
foodJsonBean.setStage_id("1");
foodJsonBean.setPage("1");
Gson gson = new Gson();
String json = gson.toJson(foodJsonBean);
RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
Call<ResponseBody> call = apiServer.post5("dish_list.php?", body, "application/json");
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
FoodBean foodBean = new Gson().fromJson(json, FoodBean.class);
btn_post5.setText(foodBean.getData().get(0).getTitle());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("TAG", "网络错误:" + t.getMessage());
}
});
}
1.三步走
1.创建实体类,然后小锤子锤一下或者点击build中的make project
@Entity
public class PersonBean {
@Id(autoincrement = true)
private long id;
@NotNull
private String name;
private String age;
2.在工程gradle中添加两个配置
buildscript {
repositories {
google()
jcenter()
mavenCentral()// 添加的代码
}
dependencies {
classpath'com.android.tools.build:gradle:3.4.1'
classpath'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
3.在项目gradle中添加三个(一个插件,一个依赖,一个基本配置)代码如下
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
implementation 'org.greenrobot:greendao:3.2.2' // add library
greendao{
schemaVersion 1 //数据库版本号
daoPackage 'com.example.greendao.dao' //数据库全路径
targetGenDir 'src/main/java' //存放位置
}
2.创建一个数据库工具类DbHelper,四步走以及创建增删改查方法
public class DbHelper {
private static DbHelper instance ;
private final PersonBeanDao personBeanDao;
public static DbHelper getInstance() {
if(instance==null){
synchronized (DbHelper.class){
if(instance==null){
instance=new DbHelper();
}
}
}
return instance;
}
private DbHelper() {
//创建数据库
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(GreenDaoApplicion.getApp(), "person.db");
//获取读写对象
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
//获取管理器
DaoSession daoSession = daoMaster.newSession();
//获取表对象
personBeanDao = daoSession.getPersonBeanDao();
}
public void insert(PersonBean personBean){
personBeanDao.insertOrReplace(personBean);
}
public void delete(PersonBean personBean){
personBeanDao.delete(personBean);
}
public void update(PersonBean personBean){
personBeanDao.update(personBean);
}
public List<PersonBean> queryAll(){
List<PersonBean> list = personBeanDao.queryBuilder().list();
return list;
}
}
插入方法注意要用insertOrReplace
public void insert(PersonBean personBean){
personBeanDao.insertOrReplace(personBean);
}
3.创建一个GreenDaoApplicion,提供全局上下文
public class GreenDaoApplicion extends Application {
private static GreenDaoApplicion app;
@Override
public void onCreate() {
super.onCreate();
app=this;
}
public static GreenDaoApplicion getApp() {
return app;
}
}
一定要注册Applicion,防止报空
<application
android:name=".GreenDaoApplicion"
4.在activity中直接单例调方法
查询方法提前给实体类手动添加toString方法
private void update() {
PersonBean personBean = new PersonBean();
personBean.setId((long)2);
personBean.setName("魏晨"+2);
personBean.setAge(String.valueOf(2));
DbHelper.getInstance().update(personBean);
}
private void query() {
List<PersonBean> list = DbHelper.getInstance().queryAll();
for (int i = 0; i <list.size() ; i++) {
Log.i("TAG", "查询结果:"+list.get(i));
}
}
private void delete() {
for (int i = 0; i < 5; i++) {
PersonBean personBean = new PersonBean();
personBean.setId((long)3);
personBean.setName("高颜值"+3);
personBean.setAge(String.valueOf(3));
DbHelper.getInstance().delete(personBean);
}
}
private void insert() {
for (int i = 0; i < 5; i++) {
PersonBean personBean = new PersonBean();
personBean.setId((long)i);
personBean.setName("高颜值"+i);
personBean.setAge(String.valueOf(i));
DbHelper.getInstance().insert(personBean);
}
}
1.GreenDao三步走一样
2.判断是否有值
private boolean isHased(SqlBean sqlBean) {
List<SqlBean> list = sqlBeanDao.queryBuilder()
.where(SqlBeanDao.Properties.Title.eq(sqlBean.getTitle()))
.list();
if (list.size() > 0) {
return true;
} else {
return false;
}
}
3.新的增删改查
public long insert(SqlBean sqlBean) {
if (!isHased(sqlBean)) {
long l = sqlBeanDao.insertOrReplace(sqlBean);
return l;
} else {
return -1;
}
}
public boolean delete(SqlBean sqlBean){
if(isHased(sqlBean)){
sqlBeanDao.delete(sqlBean);
return true;
}else{
return false;
}
}
public List<SqlBean> query(){
List<SqlBean> list = sqlBeanDao.queryBuilder().list();
return list;
}
public boolean update(SqlBean sqlBean){
if(isHased(sqlBean)){
sqlBeanDao.update(sqlBean);
return true;
}else{
return false;
}
}
4.懒加载
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
initData();
} else {
if (lists != null && lists.size() > 0) {
lists.clear();
}
}
}
5.在适配器里可以写一个方法,fragment直接调方法即可
public void updataData(List<SqlBean> data) {
lists.clear();
if (data != null) {
lists.addAll(data);
}
notifyDataSetChanged();
}
1.创建一个MigrationHelper,主要是过创建一个临时表,将旧表的数据迁移到新表中(代码如下)
public class MigrationHelper {
public static boolean DEBUG = false;
private static String TAG = "MigrationHelper";
private static final String SQLITE_MASTER = "sqlite_master";
private static final String SQLITE_TEMP_MASTER = "sqlite_temp_master";
private static WeakReference<ReCreateAllTableListener> weakListener;
public interface ReCreateAllTableListener{
void onCreateAllTables(Database db, boolean ifNotExists);
void onDropAllTables(Database db, boolean ifExists);
}
public static void migrate(SQLiteDatabase db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
printLog("【The Old Database Version】" + db.getVersion());
Database database = new StandardDatabase(db);
migrate(database, daoClasses);
}
public static void migrate(SQLiteDatabase db, ReCreateAllTableListener listener, Class<? extends AbstractDao<?, ?>>... daoClasses) {
weakListener = new WeakReference<>(listener);
migrate(db, daoClasses);
}
public static void migrate(Database database, ReCreateAllTableListener listener, Class<? extends AbstractDao<?, ?>>... daoClasses) {
weakListener = new WeakReference<>(listener);
migrate(database, daoClasses);
}
public static void migrate(Database database, Class<? extends AbstractDao<?, ?>>... daoClasses) {
printLog("【Generate temp table】start");
generateTempTables(database, daoClasses);
printLog("【Generate temp table】complete");
ReCreateAllTableListener listener = null;
if (weakListener != null) {
listener = weakListener.get();
}
if (listener != null) {
listener.onDropAllTables(database, true);
printLog("【Drop all table by listener】");
listener.onCreateAllTables(database, false);
printLog("【Create all table by listener】");
} else {
dropAllTables(database, true, daoClasses);
createAllTables(database, false, daoClasses);
}
printLog("【Restore data】start");
restoreData(database, daoClasses);
printLog("【Restore data】complete");
}
private static void generateTempTables(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for (int i = 0; i < daoClasses.length; i++) {
String tempTableName = null;
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String tableName = daoConfig.tablename;
if (!isTableExists(db, false, tableName)) {
printLog("【New Table】" + tableName);
continue;
}
try {
tempTableName = daoConfig.tablename.concat("_TEMP");
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE IF EXISTS ").append(tempTableName).append(";");
db.execSQL(dropTableStringBuilder.toString());
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("CREATE TEMPORARY TABLE ").append(tempTableName);
insertTableStringBuilder.append(" AS SELECT * FROM `").append(tableName).append("`;");
db.execSQL(insertTableStringBuilder.toString());
printLog("【Table】" + tableName +"\n ---Columns-->"+getColumnsStr(daoConfig));
printLog("【Generate temp table】" + tempTableName);
} catch (SQLException e) {
Log.e(TAG, "【Failed to generate temp table】" + tempTableName, e);
}
}
}
private static boolean isTableExists(Database db, boolean isTemp, String tableName) {
if (db == null || TextUtils.isEmpty(tableName)) {
return false;
}
String dbName = isTemp ? SQLITE_TEMP_MASTER : SQLITE_MASTER;
String sql = "SELECT COUNT(*) FROM `" + dbName + "` WHERE type = ? AND name = ?";
Cursor cursor=null;
int count = 0;
try {
cursor = db.rawQuery(sql, new String[]{"table", tableName});
if (cursor == null || !cursor.moveToFirst()) {
return false;
}
count = cursor.getInt(0);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
}
return count > 0;
}
private static String getColumnsStr(DaoConfig daoConfig) {
if (daoConfig == null) {
return "no columns";
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < daoConfig.allColumns.length; i++) {
builder.append(daoConfig.allColumns[i]);
builder.append(",");
}
if (builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
return builder.toString();
}
private static void dropAllTables(Database db, boolean ifExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) {
reflectMethod(db, "dropTable", ifExists, daoClasses);
printLog("【Drop all table by reflect】");
}
private static void createAllTables(Database db, boolean ifNotExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) {
reflectMethod(db, "createTable", ifNotExists, daoClasses);
printLog("【Create all table by reflect】");
}
/**
* dao class already define the sql exec method, so just invoke it
*/
private static void reflectMethod(Database db, String methodName, boolean isExists, @NonNull Class<? extends AbstractDao<?, ?>>... daoClasses) {
if (daoClasses.length < 1) {
return;
}
try {
for (Class cls : daoClasses) {
Method method = cls.getDeclaredMethod(methodName, Database.class, boolean.class);
method.invoke(null, db, isExists);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private static void restoreData(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
for (int i = 0; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
if (!isTableExists(db, true, tempTableName)) {
continue;
}
try {
// get all columns from tempTable, take careful to use the columns list
List<TableInfo> newTableInfos = TableInfo.getTableInfo(db, tableName);
List<TableInfo> tempTableInfos = TableInfo.getTableInfo(db, tempTableName);
ArrayList<String> selectColumns = new ArrayList<>(newTableInfos.size());
ArrayList<String> intoColumns = new ArrayList<>(newTableInfos.size());
for (TableInfo tableInfo : tempTableInfos) {
if (newTableInfos.contains(tableInfo)) {
String column = '`' + tableInfo.name + '`';
intoColumns.add(column);
selectColumns.add(column);
}
}
// NOT NULL columns list
for (TableInfo tableInfo : newTableInfos) {
if (tableInfo.notnull && !tempTableInfos.contains(tableInfo)) {
String column = '`' + tableInfo.name + '`';
intoColumns.add(column);
String value;
if (tableInfo.dfltValue != null) {
value = "'" + tableInfo.dfltValue + "' AS ";
} else {
value = "'' AS ";
}
selectColumns.add(value + column);
}
}
if (intoColumns.size() != 0) {
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("REPLACE INTO `").append(tableName).append("` (");
insertTableStringBuilder.append(TextUtils.join(",", intoColumns));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", selectColumns));
insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");
db.execSQL(insertTableStringBuilder.toString());
printLog("【Restore data】 to " + tableName);
}
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);
db.execSQL(dropTableStringBuilder.toString());
printLog("【Drop temp table】" + tempTableName);
} catch (SQLException e) {
Log.e(TAG, "【Failed to restore data from temp table 】" + tempTableName, e);
}
}
}
private static List<String> getColumns(Database db, String tableName) {
List<String> columns = null;
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 0", null);
if (null != cursor && cursor.getColumnCount() > 0) {
columns = Arrays.asList(cursor.getColumnNames());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
if (null == columns)
columns = new ArrayList<>();
}
return columns;
}
private static void printLog(String info){
if(DEBUG){
Log.d(TAG, info);
}
}
private static class TableInfo {
int cid;
String name;
String type;
boolean notnull;
String dfltValue;
boolean pk;
@Override
public boolean equals(Object o) {
return this == o
|| o != null
&& getClass() == o.getClass()
&& name.equals(((TableInfo) o).name);
}
@Override
public String toString() {
return "TableInfo{" +
"cid=" + cid +
", name='" + name + '\'' +
", type='" + type + '\'' +
", notnull=" + notnull +
", dfltValue='" + dfltValue + '\'' +
", pk=" + pk +
'}';
}
private static List<TableInfo> getTableInfo(Database db, String tableName) {
String sql = "PRAGMA table_info(`" + tableName + "`)";
printLog(sql);
Cursor cursor = db.rawQuery(sql, null);
if (cursor == null)
return new ArrayList<>();
TableInfo tableInfo;
List<TableInfo> tableInfos = new ArrayList<>();
while (cursor.moveToNext()) {
tableInfo = new TableInfo();
tableInfo.cid = cursor.getInt(0);
tableInfo.name = cursor.getString(1);
tableInfo.type = cursor.getString(2);
tableInfo.notnull = cursor.getInt(3) == 1;
tableInfo.dfltValue = cursor.getString(4);
tableInfo.pk = cursor.getInt(5) == 1;
tableInfos.add(tableInfo);
// printLog(tableName + ":" + tableInfo);
}
cursor.close();
return tableInfos;
}
}
}
2.新建一个类GreenDaoHelper,继承DaoMaster.OpenHelper,重写onUpgrade(Database db, int oldVersion, int newVersion)方法,在该方法中使用MigrationHelper进行数据库升级以及数据迁移
public class GreenDaoHelper extends DaoMaster.OpenHelper {
public GreenDaoHelper(Context context, String name) {
super(context, name);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
@Override
public void onCreateAllTables(Database db, boolean ifNotExists) {
DaoMaster.createAllTables(db, ifNotExists);
}
@Override
public void onDropAllTables(Database db, boolean ifExists) {
DaoMaster.dropAllTables(db, ifExists);
}
}, PersonBeanDao.class);
}
}
然后使用GreenDaoHelper替代DaoMaster.OpenHelper来进行创建数据库等操作
private DbHelper() {
//创建数据库
//DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(GreenDaoApplicion.getApp(), "person.db");
GreenDaoHelper daoHelper = new GreenDaoHelper(GreenDaoApplicion.getApp(), "person.db");
//获取读写对象
DaoMaster daoMaster = new DaoMaster(daoHelper.getWritableDatabase());
//获取管理器
DaoSession daoSession = daoMaster.newSession();
//获取表对象
personBeanDao = daoSession.getPersonBeanDao();
}
3.①在表实体类中,调整其中的变量(表字段),一般就是新增/删除/修改字段,例如:添加一个sex
②将原本自动生成的构造方法以及getter/setter方法删除,重新Build—>Make Project或者锤一下进行生成。
@Entity
public class PersonBean {
@Id(autoincrement = true)
private long id;
@NotNull
private String name;
private String age;
private String sex;
4.修改项目gradle中数据库的版本号schemaVersion ,递增加1即可,最后运行app
greendao{
schemaVersion 2 //数据库版本号
daoPackage 'com.example.greendao.dao' //数据库全路径
targetGenDir 'src/main/java' //存放位置
}
1.添加依赖和权限
2.GreenDao三步走
1:创建实体类,然后小锤子锤一下或者点击build中的make project
@Entity
public class PersonBean {
@Id(autoincrement = true)
private long id;
@NotNull
private String name;
private String age;
2.在工程gradle中添加两个配置
buildscript {
repositories {
google()
jcenter()
mavenCentral()// 添加的代码
}
dependencies {
classpath'com.android.tools.build:gradle:3.4.1'
classpath'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
3.在项目gradle中添加三个(一个插件,一个依赖,一个基本配置)代码如下
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
implementation 'org.greenrobot:greendao:3.2.2' // add library
greendao{
schemaVersion 1 //数据库版本号
daoPackage 'com.example.greendao.dao' //数据库全路径
targetGenDir 'src/main/java' //存放位置
}
3.提供全局上下文(一定不要忘记注册----防止报空)
public class GreenDaoApplicion extends Application {
private static GreenDaoApplicion app;
@Override
public void onCreate() {
super.onCreate();
app=this;
}
public static GreenDaoApplicion getApp() {
return app;
}
}
注册 注册 注册(千万不要忘记)
<application
android:name=".GreenDaoApplicion"
4.创建数据库工具类
判断是否有值
private boolean isHased(SqlBean sqlBean) {
List<SqlBean> list = sqlBeanDao.queryBuilder()
.where(SqlBeanDao.Properties.Title.eq(sqlBean.getTitle()))
.list();
if (list.size() > 0) {
return true;
} else {
return false;
}
}
增删改查
public long insert(SqlBean sqlBean) {
if (!isHased(sqlBean)) {
long l = sqlBeanDao.insertOrReplace(sqlBean);
return l;
} else {
return -1;
}
}
public boolean delete(SqlBean sqlBean){
if(isHased(sqlBean)){
sqlBeanDao.delete(sqlBean);
return true;
}else{
return false;
}
}
public List<SqlBean> query(){
List<SqlBean> list = sqlBeanDao.queryBuilder().list();
return list;
}
public boolean update(SqlBean sqlBean){
if(isHased(sqlBean)){
sqlBeanDao.update(sqlBean);
return true;
}else{
return false;
}
}
懒加载
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
initData();
} else {
if (lists != null && lists.size() > 0) {
lists.clear();
}
}
}
在适配器里可以写一个方法,fragment直接调方法即可
public void updataData(List<SqlBean> data) {
lists.clear();
if (data != null) {
lists.addAll(data);
}
notifyDataSetChanged();
}
5.创建TVF
6.实现首页功能:retrofit实现网络请求、点击事件、插入数据
插入数据
homeAdapter.setOnItemClickListener(new HomeAdapter.onItemClickListener() {
@Override
public void onItemClick(int i) {
FoodBean.DataBean dataBean = lists.get(i);
SqlBean sqlBean = new SqlBean();
sqlBean.setId(i);
sqlBean.setTitle(dataBean.getTitle());
sqlBean.setUrlPath(dataBean.getPic());
long insert = DbHelper.getInstance().insert(sqlBean);
if(insert>=0){
Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "收藏失败", Toast.LENGTH_SHORT).show();
}
}
});
7.实现收藏功能:查询数据库、删除数据、viewpager结合fragment实现懒加载
查询数据
private void initData() {
List<SqlBean> list = DbHelper.getInstance().query();
//调用适配器里创建的updataData方法
adapter.updataData(list);
//lists.addAll(list);
//adapter.notifyDataSetChanged();
}
删除数据
adapter.setOnItemClickListener(new CollectionAdapter.OnItemClickListener() {
@Override
public void onItemClick(int i) {
//删除数据库
SqlBean sqlBean = lists.get(i);
boolean delete = DbHelper.getInstance().delete(sqlBean);
//删除条目
lists.remove(i);
adapter.notifyDataSetChanged();
if (delete) {
Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "删除失败", Toast.LENGTH_SHORT).show();
}
}
});
1.导入依赖
RxJava依赖库
implementation 'io.reactivex.rxjava2:rxjava:2.2.4'//rxjava自己的依赖
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'//针对android的依赖
implementation 'com.squareup.retrofit2:retrofit:2.5.0'//retrofit 库
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'//数据解析器依赖(不用new gson)
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'//网络适配器,retrofit和rxjava结合使用
2.xJava定义、优点、作用、三个概念、原理、事件、调度器
3.RxJava使用:基本使用、链式使用
4.RxJava结合retrofit实现网络请求
private void net() {
//获取retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
//获取接口服务对象
ApiService apiService = retrofit.create(ApiService.class);
//获取被观察者
Observable<FoodBean> observable = apiService.get();
//被观察者订阅观察者
observable
.subscribeOn(Schedulers.io())//事件产生路线
.observeOn(AndroidSchedulers.mainThread())//消费事件的线路
.subscribe(new Observer<FoodBean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(FoodBean foodBean) {
btn_rxjava_retrofit.setText(foodBean.getData().get(3).getTitle());
}
@Override
public void onError(Throwable e) {
Log.i("TAG", "网络错误:"+e.getMessage());
}
@Override
public void onComplete() {
}
});
}
5.其他操作符
1.架构模式有几类
MVC:
视图层(View): 对应于xml布局文件和java代码动态view部分
控制层(Controller)
模型层(Model): 网络请求 数据库处理 io操作
MVP:
M层: 模型层(Model),此层和MVC中的M层作用类似.主要是实体类,数据库,网络等存在的层面
V层: 视图层(View),在MVC中V层只包含XML文件,而MVP中V层包含XML,Activity和Fragment三者.理论上V层不涉及任何逻辑,只负责界面,逻辑处理放到M层
P层: 通知层(Presenter),P层的主要作用就是连接V层和M层,起到一个通知传递数据的作用
MVP原理:
用户触碰界面触发事件,view把事件通知到Presenter,Presenter把事件在通知到model进行数据处理,处理完毕再传给Presenter,Presenter得到处理好的数据再传给view,最后view做出改变
具体流程
public interface ClickCallBack {
//设置两个方法(成功 失败)
void onSuccess(String msg);
void onFail(String error);
}
public interface ClickModel {
void click(ClickCallBack clickCallBack);
}
public class ImpClickModel implements ClickModel {
@Override
public void click(ClickCallBack clickCallBack) {
//获取数据
String content"哈哈,笑一个吧,功成名就不是目的";
String erroeContent="数据错误";
if(content.isEmpty()){
clickCallBack.onFail(erroeContent);
}else{
clickCallBack.onSuccess(content);
}
}
}
public interface ClickView {
//设置两个方法(成功 失败)
void onSuccess(String msg);
void onFail(String error);
}
public interface ClickPresenter {
void click();
}
public class ImpClickPresenter implements ClickPresenter {
private ImpClickModel impClickModel;
private ClickView clickView;
public ImpClickPresenter(ClickView clickView) {
this.clickView = clickView;
impClickModel = new ImpClickModel();
}
@Override
public void click() {
if(impClickModel!=null){
impClickModel.click(new ClickCallBack() {
@Override
public void onSuccess(String msg) {
clickView.onSuccess(msg);
}
@Override
public void onFail(String error) {
clickView.onFail(error);
}
});
}
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener, ClickView {
private Button btn_gettext;
private TextView tv_gettext;
private ImpClickPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
presenter = new ImpClickPresenter(this);
initView();
}
private void initView() {
btn_gettext = (Button) findViewById(R.id.btn_gettext);
tv_gettext = (TextView) findViewById(R.id.tv_gettext);
btn_gettext.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_gettext:
presenter.click();
break;
}
}
@Override
public void onSuccess(String msg) {
tv_gettext.setText(msg);
}
@Override
public void onFail(String error) {
tv_gettext.setText(error);
}
}
1.导入依赖
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
2.安装插件:Android ButterKnife Zelezny
3.可以绑定
@BindString(R.string.hh)
String hh;
@BindColor(R.color.colorPrimary)
int colorPrimary;