1.新建项目,在项目app下的build.gradle配置
apply plugin: 'realm-android'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "io.realm:realm-gradle-plugin:2.3.0"
}
}
//**其他包
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.orhanobut:logger:1.8'
2.自定义MyApplication
public class MyApplication extends Application {
public static Context context;
public static Realm realm;
@Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
// Logger.init("TAG").setLogLevel(LogLevel.FULL);
Realm.init(this);
RealmConfiguration configuration=new RealmConfiguration.Builder()
.name(RealmHelper.DB_NAME) //string 类型 的数据库名称
.schemaVersion(0)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(configuration);
}
public static Context getContext() {
return context;
}
}
3.创建bean对象 extends RealmObject, Ream无法自动增加主键,所以主键自己手动添加,用UUID.roundmUUID.tostring
public class InboundRecords extends RealmObject {
@PrimaryKey
private String uuid;
private String codeNumber;
private int amount;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getCodeNumber() {
return codeNumber;
}
public void setCodeNumber(String codeNumber) {
this.codeNumber = codeNumber;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
4.RealmHelp帮助类中获取默认的Realm对象,进行增删改查操作。
public class RealmHelper {
public static final String DB_NAME = "myRealm.realm";
private Realm mRealm;
public Context context;
public RealmHelper(Context context) {
mRealm = Realm.getDefaultInstance();
this.context=context;
}
/**
*同步插 入
* @param object
* @return
*/
public boolean insert_Inbound(RealmObject object) {
try {
mRealm.beginTransaction();
mRealm.insert(object);
mRealm.commitTransaction();
return true;
} catch (Exception e) {
e.printStackTrace();
mRealm.cancelTransaction();
return false;
}
}
/**
* 查询(全查)
* @param object
* @return
*/
public List<InboundRecords>queryAll_Inbound() {
RealmResults<InboundRecords> datas = mRealm.where(InboundRecords.class).findAll();
return mRealm.copyFromRealm(datas);
}
/**
* 条件查询(一)
* @return
*/
public SummaryTable queryByCode(String code) {
SummaryTable datas = mRealm.where(SummaryTable.class).equalTo("codeNumber", code).findFirst();
return datas;
}
/**改
*/
public void update_SummaryByCode(String code,int amount) {
SummaryTable datas = mRealm.where(SummaryTable.class).equalTo("codeNumber", code).findFirst();
mRealm.beginTransaction();
datas.setAmount(amount);
mRealm.commitTransaction();
}
public void delete_SummaryTable() {
final RealmResults<SummaryTable> results = mRealm.where(SummaryTable.class).findAll();
mRealm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
// 删除该表
realm.delete(SummaryTable.class);
}
});
}
//
// /**
// * add (增)
// */
// public void addDog(final Dog dog) {
// //复制一个对象到Realm数据库
// mRealm.beginTransaction();
// mRealm.copyToRealm(dog);
// mRealm.commitTransaction();
//
// }
// /**
// * add (异步增)
// */
// public void asyncAddPeo(final People dog) {
// RealmAsyncTask addTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
// @Override
// public void execute(Realm realm) {
// realm.copyToRealm(dog);
// }
// }, new Realm.Transaction.OnSuccess() {
// @Override
// public void onSuccess() {
// Toast.makeText(context, "成功", Toast.LENGTH_SHORT).show();
// }
// }, new Realm.Transaction.OnError() {
// @Override
// public void onError(Throwable error) {
// Toast.makeText(context, "失败", Toast.LENGTH_SHORT).show();
// }
// });
protected void onDestroy() {
if (addTask!=null&&!addTask.isCancelled()){
addTask.cancel();
}
}
// }
// /**
// * update (改)
// */
// public void updateDog(String id, String newName,int age) {
// Dog dog = mRealm.where(Dog.class).equalTo("id", id).findFirst();
// mRealm.beginTransaction();
// dog.setName(newName);
// dog.setAge(age);
// mRealm.commitTransaction();
// }
// /**
// * delete (删)
// */
// public void deleteDog(String id) {
// Dog dog = mRealm.where(Dog.class).equalTo("id", id).findFirst();
// mRealm.beginTransaction();
// dog.deleteFromRealm();
// mRealm.commitTransaction();
//
// }
// /**
// * 按照id删除制定的记录
// * @param clazz 类型
// * @param idFieldName id字段的名称
// * @param id id字段值
// * @return
// */
// public boolean deleteById2(Class<? extends RealmObject> clazz, String idFieldName, String id) {
// try {
// mRealm.beginTransaction();
// mRealm.where(clazz).equalTo(idFieldName, id).findAll().deleteFirstFromRealm();
// mRealm.commitTransaction();
// return true;
// } catch (Exception e) {
// e.printStackTrace();
// mRealm.cancelTransaction();
// return false;
// }
// }
//
// /**
// * delete (异步删)
// */
// public void asyncDeleteDog(final String id){
// mRealm.executeTransaction(new Realm.Transaction() {
// @Override
// public void execute(Realm realm) {
// Dog cat = realm.where(Dog.class).equalTo("id",id).findFirst();
// if(cat != null) {
// cat.deleteFromRealm();
// }
Dog dog=dogs.get(5);
dog.deleteFromRealm();
//删除第一个数据
dogs.deleteFirstFromRealm();
//删除最后一个数据
dogs.deleteLastFromRealm();
//删除位置为1的数据
dogs.deleteFromRealm(1);
//删除所有数据
dogs.deleteAllFromRealm();
// }
// });
// }
//
5.使用 //插入数据 【入库记录】
private void income(String myCode) {
InboundRecords info=new InboundRecords();
info.setUuid(UUID.randomUUID().toString());
info.setCodeNumber(myCode);
info.setAmount(1);
//插入数据
boolean istrue= realmHelper.insert_Inbound(info);
SummaryTable tab= realmHelper.queryByCode(myCode);//根据字段查询数据【查】
if(tab!=null&&tab.getCodeNumber()!=null&&tab.getCodeNumber().equals(myCode)){
int addAmount=tab.getAmount()+1;
realmHelper.update_SummaryByCode(myCode,addAmount);//根据字段修改数据【修改】
}else {
SummaryTable sum = new SummaryTable();
sum.setUuid(UUID.randomUUID().toString());
sum.setAmount(1);
sum.setCodeNumber(myCode);
boolean is = realmHelper.insert_SummaryTable(sum);
if (is) {
Toast.makeText(this, "成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show();
}
List<InboundRecords> myList=mRealmHelper.queryAll_Inbound();//【全查】
}
public class InboundRecords extends RealmObject {//implements Serializable
@PrimaryKey
private String uuid;
private String codeNumber;
private int amount;
private String state;
private String time;
private long long_time;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getCodeNumber() {
return codeNumber;
}
public void setCodeNumber(String codeNumber) {
this.codeNumber = codeNumber;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public long getLong_time() {
return long_time;
}
public void setLong_time(long long_time) {
this.long_time = long_time;
}
}