我想将一些数据保存到某种离线数据库中 [英] I want to save some data to some sort of offline database

查看:78
本文介绍了我想将一些数据保存到某种离线数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有2个EditText字段,其中包含一些文本,我想在以后保存和加载。这样做的最佳方法是什么?它必须保存在电话中,而不是保存在在线Internet数据库(如Firebase)上。

So I have 2 EditText fields with some text which I want to save and load in a later date. What is the best approach in doing it? It must be saved on the phone and not on an online internet database(Like Firebase).

我想到的解决方案是:

1。将其保存在一个扩展名为.txt的单个文本文件中。

a. Here I will use keywords which my code can read like <START OF DATA(x)> 
   where x is the id of the data saved.(

b. This obviously will take a long time to implement but it will make. But 
   will be a lot neater than solution #2.

2。将每个结果保存到扩展名为.txt的单独文本文件中
a。在这里,我将结果保存到其相应​​的文本文件中(例如:res0001)。

2. Save each result to separate text file with the .txt extension removed. a. Here I will save results to their corresponding text file(Ex: res0001).

b. I will use a third party file explorer to load the text contained in the 
   text file.

c. This is easier to implement than solution #1.

关于如何最好地解决我的问题的其他建议吗?也许是API?

Any other suggestions on how to best approach my problem? An API perhaps?

推荐答案

Lex_F可以使用SharedPreferences,但是如果用户清除设置中的应用程序数据或应用程序缓存,则SharedPreferences将提供默认值,而不是实际保存的值。永久存储,您可以使用SQLite数据库,但需要SQLite更多样板代码。我认为您应该尝试使用非常简单易用的realm数据库。这取决于您应该使用哪个数据库。但是我将给出真实数据库的示例,例如。

Lex_F you can use the SharedPreferences but if user clear the app data or cache of your application from setting then your SharedPreferences gives the default value rather than your actual saved value.For permanent storage, you can use the SQLite database but SQLite required more boilerplate code.I think you should try to use the realm database which is very simple to use.This up to you which database should use.But I would give the example of real database like.

public class UserInformation extends RealmObject {

private String name;
@PrimaryKey  //define the phone number as a primary key
private String phone;
private String address;
private String gmail;

public UserInformation() {
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getGmail() {
    return gmail;
}

public void setGmail(String gmail) {
    this.gmail = gmail;
}

}

现在处于任何活动

Realm realm;

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

    Realm.init(this);
    realm = Realm.getDefaultInstance();


    //insert the data into the realm database
    insert.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                realm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        //second argument represent the primary key
                        UserInformation information = realm.createObject(UserInformation.class, phone.getText().toString());
                        information.setName(name.getText().toString());
                        information.setGmail(email.getText().toString());
                       information.setAddress(address.getText().toString());
                        realm.copyToRealm(information);

                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(MainActivity.this, "Successfully inserted data..", Toast.LENGTH_SHORT).show();
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        Toast.makeText(MainActivity.this, "Something wrong please try again later..", Toast.LENGTH_SHORT).show();

                    }
                });

            }
    });

    update.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            realm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                        RealmResults<UserInformation> query = realm.where(UserInformation.class).equalTo("phone", phone.getText().toString()).findAll();
                        //if query not gives any result then query.size() return give 0 value
                        if (query.size() == 0) {
                            ToastLogUtil.toastmessage(MainActivity.this, "You entered wrong information or might be your entered phone no not matches existing information");
                        } else {
                            for (UserInformation info : query) {
                                info.setName(name.getText().toString());
                              //  info.setPhone(phone.getText().toString());
                                info.setGmail(email.getText().toString());
                                info.setAddress(address.getText().toString());
                                realm.copyToRealm(info);
                            }
                            ToastLogUtil.toastmessage(MainActivity.this, "Successfully updated data");
                        }
                }
            }, new Realm.Transaction.OnSuccess() {
                @Override
                public void onSuccess() {
                    ToastLogUtil.toastmessage(MainActivity.this, "Your Information Updated Successfully..");

                }
            }, new Realm.Transaction.OnError() {
                @Override
                public void onError(Throwable error) {
                    clearData();
                    ToastLogUtil.toastmessage(MainActivity.this, "Your Information not Updated something wrong...");
                    ToastLogUtil.errorlog(error.toString());
                }
            });

        }
    });

     retrieve.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (TextUtils.isEmpty(name.getText().toString()) && TextUtils.isEmpty(phone.getText().toString()) && TextUtils.isEmpty(email.getText().toString()) && TextUtils.isEmpty(address.getText().toString())) {
                //at this you can retrieve all information 
                RealmResults<UserInformation> query = realm.where(UserInformation.class).findAllAsync();
                for (UserInformation info : query) {
                    text.append(info.getName() + "\n");
                    text.append(info.getPhone() + "\n");
                    text.append(info.getGmail() + "\n");
                    text.append(info.getAddress() + "\n");
                }
                ToastLogUtil.toastmessage(MainActivity.this,"retrieve all data successfully...");
            } else {
                //at this query you can retrieve specific user which have a same phone which you enter in .equalTO() method
                RealmResults<UserInformation> query = realm.where(UserInformation.class).equalTo("phone", phone.getText().toString()).findAll();
                for (UserInformation info : query) {
                    text.append(info.getName() + "\n");
                    text.append(info.getPhone() + "\n");
                    text.append(info.getGmail() + "\n");
                    text.append(info.getAddress() + "\n");
                    ToastLogUtil.toastmessage(MainActivity.this,"Retrieve "+info.getPhone()+ " data successfully...");
                }
            }
        }
    });


     delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (TextUtils.isEmpty(phone.getText().toString())) {
                ToastLogUtil.toastmessage(MainActivity.this, "Please mention the phone number you want to delete");
            } else {

                RealmResults<UserInformation> query = realm.where(UserInformation.class).equalTo("phone", phone.getText().toString()).findAllAsync();
                if (query.size() == 0) {
                     ToastLogUtil.toastmessage(MainActivity.this,"Your phone no not matches in our database phone no..");
                } else {
                    realm.beginTransaction();
                    query.deleteAllFromRealm();
                    realm.commitTransaction();
                    ToastLogUtil.toastmessage(MainActivity.this, "Delete data successfully...");
                }
            }
        }
    });

   } 

谢谢:-)

别忘了添加领域依赖项

//将类路径依赖项添加到项目级别的build.gradle文件中。

//Add the class path dependency to the project level build.gradle file.

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath "io.realm:realm-gradle-plugin:4.3.3"
}

}

//将realm-android插件应用到应用程序级别build.gradle文件的顶部。

//Apply the realm-android plugin to the top of the application level build.gradle file.

apply plugin: 'realm-android'

这篇关于我想将一些数据保存到某种离线数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆