I want to use card views in my app but I'm using Realm database, I really appreciate a brief explanation or an example. Thank you :)
Card View is User Interface that you use to show your content to the the user. For example, A card containing, the name and age of the user, image of the user etc. Whereas Realm is a mobile database, which stores the actual values of the user like name, age, path of the image and so on.
So, you use Card View to display the values and Realm to store the actual values.
More read up on Card View can be done here
and read up on Realm can be from here
public class User extends RealmObject {
#PrimaryKey
private String id;
private String firstName;
private String lastName;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
In Your activity, You can store values to the Realm object like below,
User user = new User()
user.setFirstName("John")
user.setLastName("Kennedy")
user.setAge(40)
Realm realm = Realm.getInstance(this)
realm.executeTransaction {
realm.copyToRealmOrUpdate(user)
}
//Below is written in Kotlin language. You can find similar one in Java from the link given
val userJohn: User = realm.where(User::class.java)?.equalTo("firstName", "John").findFirst()
//Values of User John can be accessed like below
println(userJohn.firstName)
println(userJohn.lastName)
println(userJohn.age)
The above is Realm Example.
Below are some of the card view examples
http://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and-cardview-on-android--cms-23465
http://javatechig.com/android/android-cardview-example
http://www.truiton.com/2015/03/android-cardview-example/
Because Realm makes the Objects for you, you simply use the getter and setter methods to populate the views on your cards. This would be done with the Adapter associated with your RecyclerView, or whatever List type View you are using.
Related
Suppose that you listen for changes on a User object via viewmodel and observable livedata like this:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel.getUser().observe(this, user -> {
// Update UI :
// Update userNameTextView
// Load profile image to imageView
// Update follower count
});
}
As observed User changes, you update the views. The actual change on object is probably just the follower count but you act like whole user object has changed Ex: setting the same image to imageview.
Isn't this bad practice and waste of resources? What should you do in this case?
One possible solution would be to use databinding for binding your User object by making it extend BaseObservable or making it's fields ObservableFields of their corresponding data types.
You can still use LiveData as the data container/channel between the View & the ViewModel for re-binding the whole User object.
And then for partial updates, you can notifyPropertyChanged on the fields you've changed, here is an example:
private static class User extends BaseObservable {
private String firstName;
private String lastName;
#Bindable
public String getFirstName() {
return this.firstName;
}
#Bindable
public String getLastName() {
return this.lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
notifyPropertyChanged(BR.firstName);
}
public void setLastName(String lastName) {
this.lastName = lastName;
notifyPropertyChanged(BR.lastName);
}
}
I use Android Room for my database. I have a title screen and when I click on a button there, my activity opens. The activity shows me a list of members saved in the database. My entity Member consists of first name, surname and balance. I can add new members. The user can set first name and surname, the balance is automatically set with the value 0. I do have another entity called transactions, where I can add transaction and link transactions with members.
If I add two new transactions for a member a, the member a's balance goes up. I can click on a member in my member activity, then I see additional information of the member. There, I can see the actual balance he has with a SUM() query in my DAO.
But I don't know, how to use that query to set Balance of a member. I also don't know where(in which class) I should use the set Balance method of the member class.
Entity Member:
#TypeConverters(Converters.class)
#Entity(tableName = "member_table")
public class Member {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "MemberID")
private long id;
#ColumnInfo(name = "FirstName")
private String firstname;
#ColumnInfo(name = "Surname")
private String surname;
#ColumnInfo(name = "MemberBalance")
private BigDecimal balance;
private boolean isSelected = false;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Member(String firstname, String surname) {
this.firstname = firstname;
this.surname = surname;
this.balance = new BigDecimal(0).setScale(2, RoundingMode.HALF_EVEN);
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
Entity Transaction:
#TypeConverters(Converters.class)
#Entity(tableName = "transaction_table")
public class Transaction {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "TransactionID")
private long id;
#ColumnInfo(name = "TransactionName")
private String transactionName;
#ColumnInfo(name = "TransactionBalance")
private BigDecimal balance;
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTransactionName() {
return transactionName;
}
public void setTransactionName(String transactionName) {
this.transactionName = transactionName;
}
public Transaction(String transactionName, BigDecimal balance) {
this.transactionName = transactionName;
this.balance = new BigDecimal(String.valueOf(balance)).setScale(2, RoundingMode.HALF_EVEN);
}
}
First picture: This is my member activity where I see the list of all members. The balance is always 0.00 because I never use setBalance() method, and the balance should be the value gotten by the getBalance() method.
Second picture: This is my transaction activity where I can see the list of all transactions.
Third picture: This activity starts when I click on a member. Then I see the member names and below all the transactions he took part. The balance of the member here is taken with a DAO-Query: SELECT SUM(TransactionBalance)FROM member_transaction_table INNER JOIN transaction_table ON transaction_table.TransactionID = member_transaction_table.Transaction_ID WHERE member_transaction_table.Member_ID =:memberid
I can't figure out how and where to let the app calculate the transactions. The value returned by the calculations should be set with the setBalance() method.
Can anybody help me with this? If you need any specific code, just write in the comments and I'll add it to this question. Thanks!
Transaction Repository:
public class TransactionRepository {
private TransactionDao mTransactionDao;
private MemberTransactionDao mMemberTransactionDao;
private LiveData<List<Transaction>> mAllTransaction;
private MemberDao mMemberDao;
TransactionRepository(Application application) {
SmartBookkeepingRoomDatabase db = SmartBookkeepingRoomDatabase.getDatabase(application);
mTransactionDao = db.transactionDao();
mMemberTransactionDao = db.memberTransactionDao();
mMemberDao = db.memberDao();
mAllTransaction = mTransactionDao.getAllTransactions();
}
public void addTransactionBalanceToMember(Member member, Transaction transaction, OnTransactionInsertedListener listener) {
insert(transaction, listener);
BigDecimal newBalance = member.getBalance().add(transaction.getBalance());
member.setBalance(newBalance);
mMemberDao.update(member);
}
LiveData<List<Transaction>> getAllTransactions() {
return mAllTransaction;
}
public void insert(Transaction transaction, OnTransactionInsertedListener listener) {
new insertAsyncTask(mTransactionDao, listener).execute(transaction);
}
}
You should probably update the balance when inserting a new transaction in the transaction_table table. You can use #Transaction to execute 2 queries in a single transaction in your DAO. Something like this should work:
#Dao
public abstract class TransactionDao {
// ...
#Transaction
public void insertTransactionForMember(Member member, Transaction transaction) {
insertTransaction(transaction);
BigDecimal newBalance = member.getBalance() + transaction.getBalance()
member.setBalance(newBalance);
updateMember(member); // implement it here or
}
}
Now this answer is not ideal. TransactionDao should not contain a method to update member. You should have a repository handle this, call 2 insert methods on 2 DAOs inside a transaction. Also, I don't see a foreign key from Transaction to Member. Adding one might be a good idea
Solved my problem with SUM() method of SQLite.
I use Android Room for my database. I have a title screen and when I click on a button there, my activity opens. The activity shows me a list of members saved in the database. My entity Member consists of first name, surname and balance. I can add new members. The user can set first name and surname, the balance is automatically set with the value 0. I do have another entity called transactions, where I can add transaction and link transactions with members.
If I add two new transactions for a member a, the member a's balance goes up. I can click on a member in my member activity, then I see additional information of the member. There, I can see the actual balance he has with a SUM() query in my DAO.
But I don't know, how to use that query to set Balance of a member. I also don't know where(in which class) I should use the set Balance method of the member class.
Can anybody help me with this? If you need any specific code, just write in the comments and I'll add it to this question. Thanks!
Entity Member:
#TypeConverters(Converters.class)
#Entity(tableName = "member_table")
public class Member {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "MemberID")
private long id;
#ColumnInfo(name = "FirstName")
private String firstname;
#ColumnInfo(name = "Surname")
private String surname;
#ColumnInfo(name = "MemberBalance")
private BigDecimal balance;
private boolean isSelected = false;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Member(String firstname, String surname) {
this.firstname = firstname;
this.surname = surname;
this.balance = new BigDecimal(0).setScale(2, RoundingMode.HALF_EVEN);
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
Entity Transaction:
#TypeConverters(Converters.class)
#Entity(tableName = "transaction_table")
public class Transaction {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "TransactionID")
private long id;
#ColumnInfo(name = "TransactionName")
private String transactionName;
#ColumnInfo(name = "TransactionBalance")
private BigDecimal balance;
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTransactionName() {
return transactionName;
}
public void setTransactionName(String transactionName) {
this.transactionName = transactionName;
}
public Transaction(String transactionName, BigDecimal balance) {
this.transactionName = transactionName;
this.balance = new BigDecimal(String.valueOf(balance)).setScale(2, RoundingMode.HALF_EVEN);
}
}
First picture: This is my member activity where I see the list of all members. The balance is always 0.00 because I never use setBalance() method, and the balance should be the value gotten by the getBalance() method.
Second picture: This is my transaction activity where I can see the list of all transactions.
Third picture: This activity starts when I click on a member. Then I see the member names and below all the transactions he took part. The balance of the member here is taken with a DAO-Query: SELECT SUM(TransactionBalance)FROM member_transaction_table INNER JOIN transaction_table ON transaction_table.TransactionID = member_transaction_table.Transaction_ID WHERE member_transaction_table.Member_ID =:memberid
I can't figure out how and where to let the app calculate the transactions. The value returned by the calculations should be set with the setBalance() method.
I would recommend not to use column balance in Member class at all as it looks like all data should be stored in this transaction entities. If you have to show balance for a particular Member you should calculate his balance every time. This approach has one major drawback it isn't effective from a performance point of view. If performance is important than having the balance column is a good idea, but you have to update the Member entity every time new transaction added to the system.
Solved my problem by setting balance when I add a transaction. So I take the value of the transaction and simply add it to my member balance.
I need to integrate Realm database in my eclipse JUNO(Android Development Tool). I used realm 0.81.1 version. I had include all library files in my android project lib folder and configured realm-0.81.1.jar in buildpath.when "java.lang.IlleagaArgumentException:User is not part of the schema for this realmrun my project it throws error ".
Here User is an class that extends RealmObject.
The User class code is given below:
public class User extends RealmObject {
#PrimaryKey
private String name;
private int age;
#Ignore
private int sessionId;
// Standard getters & setters generated by your IDEā¦
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public int getSessionId() { return sessionId; }
public void setSessionId(int dontPersist) { this.sessionId = sessionId; }
}
The error is produced when executing the following code:
Realm realm = Realm.getInstance(this);
realm.beginTransaction();
User user = realm.createObject(User.class);
user.setName("Jhon");
user.setAge(10);
realm.commitTransaction();
Please give me suggestion to work with Realm Database
Thanks in advance.
As you are using Eclipse you need to add the #RealmClass annotation manually as it doesn't support inherited annotations. So you model class must look like this:
#RealmClass
public class User extends RealmObject
{
// ...
}
Try this and let me know if it works. Thanks.
what options do i have to make single instance of all the models classes in Android application?
I have added below one of the sample model class
public class User
{
private String email;
private String name;
public String getEmail() { return this.email; }
public void setEmail(String email) { this.email = email; }
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
}
I want once data stored in Model Class, it can be retrieved in any activity class or fragment. Should i use singleton or any better approach is available ?
Will dagger2 work in this scenario ? is dagger2 alternative to creating singleton ?
Thanks