GreenDao


导依赖


utils包下

OkhttpUtils

package com.example.com.rikao0413.utils;

import android.os.Environment;

import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by linmeihui on 2018/4/13.
 */

 public class OkhttpUtils {

    private OkhttpUtils(){};
    static OkHttpClient client;


    public static OkHttpClient getInstance(){


        if (client==null) {
            //更加安全
            synchronized (OkhttpUtils.class) {
                //缓存的地方     mnt/sdcard
                File file = new File(Environment.getExternalStorageDirectory(), "cache11");
                client = new OkHttpClient().newBuilder()
                        .readTimeout(3000, TimeUnit.SECONDS)   //设置读取超时时间
                        .connectTimeout(3000, TimeUnit.SECONDS) //设置连接的超时时间

                        .cache(new Cache(file, 10 * 1024))
                        .build();
            }
        }
        return client;
    }


    /**
     * get请求
     * Callback  是一个接口
     */
    public static void doGet(String url, Callback callback){

        //1:拿到okhttpclient  对像

        OkHttpClient client = getInstance();
        //2:进行请求的操作

        Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(callback);


    }

    //post请求

    /**
     *
     * @param url  请求的地址
     * @param parms   请求的参数
     * @param callback  callback
     */
    public static void doPost(String url, Map<String,String> parms, Callback callback){

        //得到客户端的对像
        OkHttpClient client = getInstance();

        //不是FormBody,而是一个Builder
        FormBody.Builder body = new FormBody.Builder();
        //key   value
        for (String key:parms.keySet()){
            //value的值
            body.add(key,parms.get(key));
        }
        Request request = new Request.Builder()
                .url(url)
                .post(body.build())
                .build();

        client.newCall(request).enqueue(callback);

    }

    //用来上传图片的

    //url  , 图片  ,参数    Callback
    public static  void upImage(String url,File file,String filenName,Map<String,String> params,Callback callback){

        OkHttpClient client = getInstance();


        //requestBody的实现类  Formbody
        MultipartBody.Builder builder = new MultipartBody.Builder();

        if (params!=null){
            for (String key :params.keySet()){
                builder.addFormDataPart(key,params.get(key));
            }
        }

        //设置类型
        builder.setType(MultipartBody.FORM);


        builder.addFormDataPart("file",filenName, RequestBody.create(MediaType.parse("application/octet-stream"),file));

        // builder.setType(MultipartBody.FORM);
        // builder.addFormDataPart("file",filenName,RequestBody.create(MediaType.parse("application/octet-stream"),file));
        //builder.addFormDataPart("file","aa.png",builder.build());

        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();

        client.newCall(request).enqueue(callback);


    }
}


bean类---设置参数 加注解后 编译自动生成---自动生成三个类beanDao  DaoMaster  DaoSession

package com.example.com.rikao0413.utils;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;

/**
 * Created by linmeihui on 2018/4/13.
 */
@Entity
public class Bean {
    @Id(autoincrement = true)
    private Long id;
    private String name;
    @Generated(hash = 417670818)
    public Bean(Long id, String name) {
        this.id = id;
        this.name = name;
    }
    @Generated(hash = 80546095)
    public Bean() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}



MainActivity

package com.example.com.rikao0413;

import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.com.rikao0413.utils.Bean;
import com.example.com.rikao0413.utils.BeanDao;
import com.example.com.rikao0413.utils.DaoMaster;
import com.example.com.rikao0413.utils.DaoSession;
import com.example.com.rikao0413.utils.Data;
import com.example.com.rikao0413.utils.OkhttpUtils;
import com.google.gson.Gson;

import org.greenrobot.greendao.query.WhereCondition;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    String url ="http://api.tianapi.com/startup/?key=71e58b5b2f930eaf1f937407acde08fe&num=10";

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            list = (List<Data.NewslistBean>) msg.obj;

            flag = true;

            for (int i = 0; i < list.size() ; i++) {

                Bean bean = new Bean();
                bean.setName(list.get(i).getTitle());
                beanDao.insert(bean);

            }



        }
    };
    private BeanDao beanDao;
    private TextView tv_result;
    private long insert;
    private List<Bean> beans;
    private List<Data.NewslistBean> list;
    private LinearLayout li;
    private EditText tv_name;
    private Boolean flag = false;
    private EditText tv_id;

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

        tv_result = findViewById(R.id.tv_result);

        tv_name = findViewById(R.id.tv_name);

        li = findViewById(R.id.li);

        tv_id = findViewById(R.id.tv_id);

        SQLiteDatabase writableDatabase = new DaoMaster.DevOpenHelper(this, "green.db", null).getWritableDatabase();

        DaoMaster daoMaster = new DaoMaster(writableDatabase);

        DaoSession daoSession = daoMaster.newSession();

        beanDao = daoSession.getBeanDao();

        OkhttpUtils.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String string = response.body().string();

                Gson gson = new Gson();

                Data data = gson.fromJson(string, Data.class);

                Message message = Message.obtain();

                message.obj = data.getNewslist();

                handler.sendMessage(message);


            }
        });

    }

    public void add(View view) {
       /* if(!flag) {

        }else{*/
            Bean bean = new Bean();
            bean.setName(tv_name.getText().toString());
            beanDao.save(bean);

            cha();

        //}
    }

    public void select(View view) {

        cha();

    }

    public void cha(){
        beans = beanDao.loadAll();
        Toast.makeText(this,beans.size()+"",Toast.LENGTH_SHORT).show();

        for (int i = 0; i <beans.size() ; i++) {
            TextView textView = new TextView(this);


            textView.setText(beans.get(i).getName()+"");

            li.addView(textView);
        }
    }

    public void delete(View view) {

        beanDao.deleteAll();

        WhereCondition columnName = beanDao.getPkProperty().ge("columnName");

        Toast.makeText(this,columnName+"",Toast.LENGTH_SHORT).show();
        cha();


    }
}
















阅读更多
上一篇retrofit应用
下一篇MVP+xRecyclerView+Retrofit+OkHttp+RxJava
想对作者说点什么? 我来说一句

GreenDao的基本使用

2018年03月30日 5.18MB 下载

greenDAO demo

2016年12月27日 17.62MB 下载

没有更多推荐了,返回首页

关闭
关闭