我想将一些数据保存到某种脱机数据库中

时间:2018-02-20 08:09:58

标签: android database

所以我有两个带有一些文本的EditText字段,我想保存并在以后加载。这样做的最佳方法是什么?它必须保存在手机上,而不是保存在在线互联网数据库(如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扩展名。     一个。在这里,我将结果保存到相应的文本文件中(例如: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?

2 个答案:

答案 0 :(得分:1)

您可以将值保存在“首选项”中。下面的课程将让您轻松保存数据并从首选项

中进行检索
public class SessionManager {

    private SharedPreferences pref;
    private static SessionManager sessionManager;




    public static SessionManager getInstance(Context context) {
        if(sessionManager == null){
            sessionManager = new SessionManager(context);
        }
        return sessionManager;
    }


    public SessionManager(Context context) {
        String PREF_NAME = context.getResources().getString(R.string.app_name);
        this.pref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);

    }


    /**
     * Getting value for key from shared Preferences
     *
     * @param key          key for which we need to get Value
     * @param defaultValue default value to be returned if key is not exits
     * @return It will return value of key if exist and defaultValue otherwise
     */
    public String getValueFromKey(String key, String defaultValue) {
        if (pref.containsKey(key)) {
            return pref.getString(key, defaultValue);
        } else {
            return defaultValue;
        }
    }


    /**
     * Setting value for key from shared Preferences
     *
     * @param key   key for which we need to get Value
     * @param value value for the key
     */
    public void setValueFromKey(String key, String value) {
        pref.putString(key, value).apply();
    }


    /**
     * Setting value for key from shared Preferences
     *
     * @param key   key for which we need to get Value
     * @param value value for the key
     */
    public void setFlagFromKey(String key, boolean value) {
        pref.putBoolean(key, value).apply();
    }


    /**
     * To get Flag from sharedPreferences
     *
     * @param key key of flag to get
     * @return flag value for key if exist. false if not key not exist.
     */
    public boolean getFlagFromKey(String key) {
        return pref.containsKey(key) && pref.getBoolean(key, false);
    }

}

答案 1 :(得分:0)

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

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文件。

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

}

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

apply plugin: 'realm-android'