greendao+Handler+ListView实现增删改查

原创 2018年04月15日 20:40:06


1. 主页面UI显示

2. 访问网络接口获取数据

3. 通过Handler将数据发送到主线程

4. 将获取到的数据解析成实体类型

5. greendao将数据添加到数据中

6. greendao查询出来数据展示在主页面

7. greendao清空本地数据库中的数据

8. greendao修改部分数据

https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10


    1.依赖:

compile 'org.greenrobot:greendao:3.2.2'
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.google.code.gson:gson:2.2.4'
2.权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
3.主布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.dell.a0412rikao_greendao.MainActivity">

   <EditText
       android:id="@+id/edit_id"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="请输入ID"/>

    <EditText
        android:id="@+id/edit_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名"
        android:layout_marginTop="10px"/>
  <EditText
     android:id="@+id/edit_title"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:hint="请输入描述"
     android:layout_marginTop="10px"/>

    <Button
        android:id="@+id/btn_insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="新增"
        android:layout_marginTop="10px"/>
    <Button
        android:id="@+id/btn_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除"
        android:layout_marginTop="10px"/>
    <Button
        android:id="@+id/btn_updata"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="修改"
        android:layout_marginTop="10px"/>
    <Button
        android:id="@+id/btn_removeAll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="清空"
        android:layout_marginTop="10px"/>
    <Button
        android:id="@+id/btn_queryByID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询一条"
        android:layout_marginTop="10px"/>
    <Button
        android:id="@+id/btn_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询"
        android:layout_marginTop="10px"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询结果:"
        android:gravity="center_horizontal"
        android:layout_marginTop="10px"/>

 <ListView
     android:id="@+id/my_lv"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
 </ListView>

</LinearLayout>

4.Activity 的实现

package com.example.dell.a0412rikao_greendao;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.greenrobot.greendao.query.Query;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.edit_id)
    EditText edit_Id;
    @BindView(R.id.edit_name)
    EditText edit_Name;
    @BindView(R.id.btn_insert)
    Button btn_Insert;
    @BindView(R.id.btn_delete)
    Button btn_Delete;
    @BindView(R.id.btn_query)
    Button btn_Query;
    @BindView(R.id.my_lv)
    ListView my_Lv;
    @BindView(R.id.edit_title)
    EditText edit_Title;
    @BindView(R.id.btn_updata)
    Button btn_Updata;
    @BindView(R.id.btn_removeAll)
    Button btn_RemoveAll;
    @BindView(R.id.btn_queryByID)
    Button btn_QueryByID;

    private UserDao userDao;
    private List<UserBean.NewslistBean> newslist;

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            newslist = (List<UserBean.NewslistBean>) msg.obj;

            if (!jinru_yes) {

                for (int i = 0; i < newslist.size(); i++) {
                    User user = new User();
                    user.setDescription(newslist.get(i).getDescription());
                    user.setTitle(newslist.get(i).getTitle());

                    //存入同意的状态值
                    editor.putBoolean("jinru_yes", true);
                    editor.commit();

                    userDao.insert(user);
                }
            }

        }
    };
    private MyAdapter myAdapter;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private boolean jinru_yes;
    private List<User> list;


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

        //得到SharedPreferences
        sharedPreferences = getSharedPreferences("Person", MODE_PRIVATE);
        //用来操作sharedPreferences
        editor = sharedPreferences.edit();

        //进入的状态值  用于防止进入页面时,数据重复添加
        jinru_yes = sharedPreferences.getBoolean("jinru_yes", false);

        ButterKnife.bind(this);

        //通过DaoMaster拿到DaoSession,再通过DaoSession拿到UserDao
        DaoMaster master = new DaoMaster(new DaoMaster.DevOpenHelper(this, "users").getWritableDatabase());
        DaoSession session = master.newSession();
        userDao = session.getUserDao();


        //获取数据
        OkhtttpUtils.doGet("https://api.tianapi.com/wxnew/?key=fe7aac932e1e94f10a4f8d0f2d5fe924&num=10", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Gson gson = new Gson();
                UserBean userBean = gson.fromJson(json, UserBean.class);
                List<UserBean.NewslistBean> newslist = userBean.getNewslist();

                //handler发送消息
                Message msg = new Message();
                msg.obj = newslist;
                handler.sendMessage(msg);
            }
        });
    }

    @OnClick({R.id.btn_insert, R.id.btn_delete, R.id.btn_query,R.id.btn_updata,R.id.btn_queryByID,R.id.btn_removeAll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_insert:
                //插入的方法
                insert();
                //查询的方法
                query();

                break;
            case R.id.btn_delete:
                //删除的方法
                delete();
                //查询的方法
                query();

                break;
            case R.id.btn_updata:
                //修改的方法
                updata();
                //查询的方法
                query();

                break;
            case R.id.btn_removeAll:
                //清空所有的方法
                removeAll();
                //查询的方法
                query();

                break;
            case R.id.btn_queryByID:
                //查询一条的方法
                byid();

                break;
            case R.id.btn_query:
                //查询的方法
                query();

                break;
        }
    }

    //清空所有数据
    private void removeAll() {
        userDao.deleteAll();
    }


    //根据ID查询信息
    public void byid() {

        String idd = edit_Id.getText().toString();
        Long id = Long.valueOf(idd);
        User user = userDao.load(id);
        if(user!=null){
            edit_Name.setText(user.getDescription());
            edit_Title.setText(user.getTitle());
        }else{
            Toast.makeText(this,"数据不存在",Toast.LENGTH_SHORT).show();
        }
    }

    //修改的方法
    private void updata() {

        String id_up = edit_Id.getText().toString();
        Long longid_up = Long.valueOf(id_up);
        String n = edit_Name.getText().toString();
        String t = edit_Title.getText().toString();
        User user_up = new User();
        user_up.setDescription(n);
        user_up.setTitle(t);
        user_up.setId(longid_up);
        userDao.update(user_up);
    }

    //删除的方法
    public void delete() {
        String idd = edit_Id.getText().toString();
        Long id = Long.valueOf(idd);
        userDao.deleteByKey(id);
        myAdapter.notifyDataSetChanged();
    }

    //插入的方法
    public void insert() {
        String name = edit_Name.getText().toString();
        String title = edit_Title.getText().toString();
        User user = new User();
        user.setDescription(name);
        user.setTitle(title);
        userDao.insert(user);
    }

    //查询的方法
    public void query() {
        list = userDao.loadAll();

        //设置适配器
        myAdapter = new MyAdapter(MainActivity.this, list);
        my_Lv.setAdapter(myAdapter);
    }



}
5.适配器

package com.example.dell.a0412rikao_greendao;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;

public class MyAdapter extends BaseAdapter{

    Context context;
    List<User> list;

    public MyAdapter(Context context, List<User> list) {
        this.context=context;
        this.list=list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        MyViewHolder holder;
        if(view==null){
            holder = new MyViewHolder();
            view = View.inflate(context, R.layout.item, null);
            holder.id=view.findViewById(R.id.text_id);
            holder.name=view.findViewById(R.id.text_name);
            holder.title=view.findViewById(R.id.text_title);
            view.setTag(holder);
        }else{
            holder= (MyViewHolder) view.getTag();
        }

        holder.id.setText(list.get(i).getId()+"");
        holder.name.setText(list.get(i).getTitle());
        holder.title.setText(list.get(i).getDescription());

        return view;
    }
    
    class MyViewHolder{
        TextView id,title,name;
    }
}
6.网络获取数据的Bean(大)

package com.example.dell.a0412rikao_greendao;

import java.util.List;

public class UserBean {


    private int code;
    private String msg;
    private List<NewslistBean> newslist;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<NewslistBean> getNewslist() {
        return newslist;
    }

    public void setNewslist(List<NewslistBean> newslist) {
        this.newslist = newslist;
    }

    public static class NewslistBean {


        private String ctime;
        private String title;
        private String description;
        private String picUrl;
        private String url;

        public String getCtime() {
            return ctime;
        }

        public void setCtime(String ctime) {
            this.ctime = ctime;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}
7.网络获取数据的Bean(手动封装)

package com.example.dell.a0412rikao_greendao;

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

/**
 * Created by dell on 2018/4/13.
 */
@Entity
public class User {

    @Id(autoincrement = true)
    private Long id;
    private String title;
    private String description;

    @Generated(hash = 718037864)
    public User(Long id, String title, String description) {
        this.id = id;
        this.title = title;
        this.description = description;
    }
    @Generated(hash = 586692638)
    public User() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getTitle() {
        return this.title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDescription() {
        return this.description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

  
}

8.OkhhtP的封装

package com.example.dell.a0412rikao_greendao;

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;

import static android.R.string.ok;
import static android.os.Build.VERSION_CODES.M;

/**
 * Created by Administrator on 2018/3/8.
 */

public class OkhtttpUtils {

    //单例模式,把构造方法进行私有化
    private OkhtttpUtils(){};
    static  OkHttpClient client;

    public static OkHttpClient getInstance(){


        if (client==null) {
            //更加安全
            synchronized (OkhtttpUtils.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);


    }


}
9.显示数据的ListView 的条目布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10px">

<TextView
    android:id="@+id/text_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="1"/>

    <TextView
        android:id="@+id/text_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/text_id"
        android:layout_marginLeft="20px"
        android:text="孟大明白"/>

    <TextView
        android:id="@+id/text_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text_title"
        android:text="张靓颖被爆离婚:什么样的爱情,一定不能要?"/>

</RelativeLayout>


angularJS实现增删改查等

html> html lang="en"> head> meta charset="UTF-8"> title>weicytitle> script src="angular....
  • weikai_
  • weikai_
  • 2017-10-22 19:19:30
  • 265

Java实现增删改查

前言 增删改查是很多功能的基础,所以说把这个基础打好,你就能够实现更加复杂和强大的功能。 1.查询1.1整体思路 查询是一个从数据库里面加载数据到内存的过程。 1.2流程 0.配置文件的创...
  • qq_37444478
  • qq_37444478
  • 2017-09-16 21:46:40
  • 530

JavaScript之实现基本的增删改查功能

开心一笑 听说这两天,全国都很冷。福建人说1度好冷,北京人笑了:我们这零下17度。黑龙江人也笑了:我们这零下33度。呼伦贝尔人听到哈哈大笑:我们这零下43度。福建人听完冷笑一声:我说的是室内,室内,...
  • huangwenyi1010
  • huangwenyi1010
  • 2016-05-06 17:57:10
  • 13943

mybatis系列一:mybatis实现增删改查

Java实例-Mybatis的增删改查
  • wanlong360599336
  • wanlong360599336
  • 2017-05-04 16:47:54
  • 2202

SpringMVC实现的简单的增删改查

  • 2015年01月21日 14:19
  • 12.54MB
  • 下载

java web程序实现增删改查

  • 2018年03月07日 13:46
  • 811KB
  • 下载

struts2的增删改查

刚毕业不久,现在公司用的是spring mvc框架,导致很长时间没有写strust2了,现在都有些忘记了,所以要常复习哦!花了大半天的时候用struts2字了增删改功能 第一步:导jar包   ...
  • xiaoya13144111
  • xiaoya13144111
  • 2012-10-24 15:29:50
  • 3957

学习中写的jsf实现的增删改查示例

  • 2008年12月09日 09:45
  • 11.49MB
  • 下载

ssm实现增删改查

过程中遇到的问题 在完成添加用户的时候出现了一个很奇怪的问题,以ajax的put方式请求时相关的controller拿不到请求体中的data。查了很久也不是很明吧是为什么,只是了解怎么去解决这个问题...
  • godwei_ding
  • godwei_ding
  • 2017-09-06 22:19:42
  • 495

jsp连接数据库以及前端网页实现对数据库的增删改查

//web首页,显示登录注册页面 QQ登录页面              账户:         密码:         验证码         登录  ...
  • ting_163
  • ting_163
  • 2017-07-22 20:23:39
  • 1147
收藏助手
不良信息举报
您举报文章:greendao+Handler+ListView实现增删改查
举报原因:
原因补充:

(最多只允许输入30个字)