GreenDao + 请求网络数据添加到数据库 + 新增+删除 +查询

本文介绍如何在Android项目中使用GreenDAO进行数据库操作,包括数据库配置、实体类定义及基本的CRUD操作,并实现了从网络获取数据并保存到本地数据库的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

buildscript {

    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}






apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "*************"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    greendao {
        schemaVersion 1
        daoPackage 'com.anye.greendao.gen'
        targetGenDir 'src/main/java'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile'org.greenrobot:greendao:3.0.1'
    compile'org.greenrobot:greendao-generator:3.0.0'
    compile 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    compile 'com.squareup.okhttp3:okhttp:3.9.0'
    implementation 'com.google.code.gson:gson:2.8.2'
}


User

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

/**
 * Created by lenovo on 2017/12/01.
 */

@Entity
public class User {
    @Id
    Long id;
    String name;

    @Generated(hash = 873297011)
    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    @Generated(hash = 586692638)
    public User() {
    }

    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}



点击Build -> Make Project 生成 greendao包

activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="greenDao lib test" />

        <EditText
            android:id="@+id/cid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入用户id" />

        <EditText
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入用户名" />

        <Button
            android:id="@+id/add"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="新增" />

        <Button
            android:id="@+id/del"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="删除" />

        <Button
            android:id="@+id/search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="查询" />

        <TextView
            android:id="@+id/result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="查询结果" />
        <TextView
            android:id="@+id/context"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>


Bean

根据接口自己封装



MainActivity

package ***************;

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

import com.anye.greendao.gen.DaoMaster;
import com.anye.greendao.gen.DaoSession;
import com.anye.greendao.gen.UserDao;
import com.google.gson.Gson;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.cid)
    EditText cid;
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.add)
    Button insert;
    @BindView(R.id.del)
    Button deleteByKey;
    @BindView(R.id.search)
    Button loadAll;
    @BindView(R.id.context)
    TextView context;
    private UserDao userDao;
    List<Bean.DataBean> data;
    private boolean b=false;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Gson gson = new Gson();
            data = gson.fromJson((String) msg.obj, Bean.class).getData();
            for (int i = 0; i < data.size(); i++) {

                //将网络上请求到的 数据 添加到数据库
                userDao.insert(new User((long) data.get(i).getCid(), data.get(i).getName()));
            }
        }
    };

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

        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "db", null);
        SQLiteDatabase sqLiteDatabase = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(sqLiteDatabase);
        DaoSession daoSession = daoMaster.newSession();
        userDao = daoSession.getUserDao();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("https://www.******.cn/product/getCatagory").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                Message message = Message.obtain();
                message.obj = response.body().string();
                handler.sendMessage(message);
            }

        });
    }

    @OnClick({R.id.add, R.id.del, R.id.search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add:
                for (int i = 0; i < data.size(); i++) {
                    String s = cid.getText().toString().trim();
                    int aa = Integer.parseInt(s);
                    if (aa != data.get(i).getIshome()) {
                        b = true;

                    }else {
                        Toast.makeText(this, "id重复"+data.size(), Toast.LENGTH_SHORT).show();
                        b = false;
                        break;
                    }
                }
                if (b == true) {
                    if (!"".equals(cid.getText().toString()) && !"".equals(name.getText().toString())) {
                        userDao.insert(new User(Long.parseLong(cid.getText().toString()), name.getText().toString()));
                        Toast.makeText(this, "id不重复", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.del:
                if (!"".equals(cid.getText().toString())) {
                    userDao.deleteByKey(Long.parseLong(cid.getText().toString()));
                }
                break;
            case R.id.search:
                List<User> users = userDao.loadAll();
                context.setText(users.toString());
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        userDao.deleteAll();
    }
}


权限加一个网络访问权限就可以了



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值