Last active
February 9, 2019 11:40
-
-
Save donrokzon/ef839001930dc22e833a525cd994e3d2 to your computer and use it in GitHub Desktop.
realm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
classpath "io.realm:realm-gradle-plugin:5.3.0" | |
apply plugin: 'realm-android' | |
realm { | |
syncEnabled = true; | |
} | |
public class RealmActivity extends AppCompatActivity implements View.OnClickListener { | |
Realm realm; | |
Button button; | |
EditText editText; | |
String s = ""; | |
TextView textView; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_realm); | |
button = findViewById(R.id.button); | |
editText = findViewById(R.id.editText); | |
textView = findViewById(R.id.textView); | |
button.setOnClickListener(this); | |
Realm.init(this); | |
realm = Realm.getDefaultInstance(); | |
read(); | |
} | |
@Override | |
protected void onDestroy() { | |
realm.close(); | |
super.onDestroy(); | |
} | |
private void read() { | |
textView.setText(""); | |
RealmResults<RealmObjectName> results = realm.where(RealmObjectName.class).findAll(); | |
for (RealmObjectName name : results) { | |
s += name.getName() + "\n"; | |
} | |
textView.setText(s); | |
recyclerAdapter.notifyDataSetChanged(); | |
} | |
public void writeToDIsk() { | |
realm.beginTransaction(); | |
RealmObjectName nameRealmObject = realm.createObject(RealmObjectName.class); | |
nameRealmObject.setName(editText.getText().toString()); | |
realm.commitTransaction(); | |
} | |
//or | |
public void writeToDIsk() { | |
realm.executeTransaction(new Realm.Transaction() { | |
@Override | |
public void execute(Realm realm) { | |
realm.createObject(RealmObjectName.class).setName(editText.getText().toString()); | |
} | |
}); | |
} | |
public void deleteFromDatabase(final int index){ | |
realm.executeTransaction(new Realm.Transaction() { | |
@Override | |
public void execute(Realm realm) { | |
RealmResults<Model> result = realm.where(Model.class).findAll(); | |
result.deleteFromRealm(index); | |
readDiskData(); | |
} | |
}); | |
} | |
@Override | |
protected void onStart() { | |
super.onStart(); | |
} | |
@Override | |
public void onClick(View v) { | |
if (editText.getText().toString().length() > 0) { | |
writeToDIsk(); | |
} else { | |
Toast.makeText(this, "Type something..", Toast.LENGTH_SHORT).show(); | |
} | |
editText.setText(""); | |
read(); | |
} | |
} | |
////// | |
public class RealmObjectName extends RealmObject { | |
private String name; | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment