I Want To Save Some Data To Some Sort Of Offline Database
Solution 1:
You can save the value in Preferences. Below class will be make easy for you to save data and retrive it from Preferences
publicclassSessionManager {
privateSharedPreferences pref;
privatestaticSessionManager sessionManager;
publicstaticSessionManagergetInstance(Context context) {
if(sessionManager == null){
sessionManager = newSessionManager(context);
}
return sessionManager;
}
publicSessionManager(Context context) {
StringPREF_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
*/publicStringgetValueFromKey(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
*/publicvoidsetValueFromKey(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
*/publicvoidsetFlagFromKey(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.
*/publicbooleangetFlagFromKey(String key) {
return pref.containsKey(key) && pref.getBoolean(key, false);
}
}
Solution 2:
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.
publicclassUserInformationextendsRealmObject {
privateString name;
@PrimaryKey//define the phone number as a primary keyprivateString phone;
privateString address;
privateString gmail;
publicUserInformation() {
}
publicStringgetName() {
return name;
}
publicvoidsetName(String name) {
this.name = name;
}
publicStringgetPhone() {
return phone;
}
publicvoidsetPhone(String phone) {
this.phone = phone;
}
publicStringgetAddress() {
return address;
}
publicvoidsetAddress(String address) {
this.address = address;
}
publicStringgetGmail() {
return gmail;
}
publicvoidsetGmail(String gmail) {
this.gmail = gmail;
}
}
Now in the any activity
Realm realm;
@OverrideprotectedvoidonCreate(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(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
realm.executeTransactionAsync(newRealm.Transaction() {
@Overridepublicvoidexecute(Realm realm) {
//second argument represent the primary keyUserInformation 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);
}
}, newRealm.Transaction.OnSuccess() {
@OverridepublicvoidonSuccess() {
Toast.makeText(MainActivity.this, "Successfully inserted data..", Toast.LENGTH_SHORT).show();
}
}, newRealm.Transaction.OnError() {
@OverridepublicvoidonError(Throwable error) {
Toast.makeText(MainActivity.this, "Something wrong please try again later..", Toast.LENGTH_SHORT).show();
}
});
}
});
update.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
realm.executeTransactionAsync(newRealm.Transaction() {
@Overridepublicvoidexecute(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 valueif (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");
}
}
}, newRealm.Transaction.OnSuccess() {
@OverridepublicvoidonSuccess() {
ToastLogUtil.toastmessage(MainActivity.this, "Your Information Updated Successfully..");
}
}, newRealm.Transaction.OnError() {
@OverridepublicvoidonError(Throwable error) {
clearData();
ToastLogUtil.toastmessage(MainActivity.this, "Your Information not Updated something wrong...");
ToastLogUtil.errorlog(error.toString());
}
});
}
});
retrieve.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(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() methodRealmResults<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(newView.OnClickListener() {
@OverridepublicvoidonClick(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...");
}
}
}
});
}
Thank you :-)
Not forget to add the realm dependencies
//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"
}
}
//Apply the realm-android plugin to the top of the application level build.gradle file.
apply plugin: 'realm-android'
Post a Comment for "I Want To Save Some Data To Some Sort Of Offline Database"