DEV Community

EdRome
EdRome

Posted on

How to create an Android App: Android Room part 2

Here we are one more week to continue with the previous post

In the last post we design a database of one entity to store user profile. This time we’ll make usage of it.

Let’s start adding a type converter file, not added last week. This is necessary to store date data types.

import androidx.room.TypeConverter;

import java.util.Date;

public class Converters {

    @TypeConverter
    public static Date fromTimestamp(Long value) {
        return value == null ? null : new Date(value);
    }

    @TypeConverter
    public static Long dateToTimestamp(Date date) {
        return date == null ? null : date.getTime();
    }


}

Then, onto the room file add type converter annotation and change version if you already compile the project.

@Database(entities = {profileModel.class}, version = 2, exportSchema = false)
@TypeConverters({Converters.class})
public abstract class databaseRoom extends RoomDatabase {
    ...
}

Modify Main Activity calling a POJO's instance and calling method getProfile.

  • The constructor takes Application as parameter.
  • getProfile method takes an ID as parameter
profilePojo = new profilePOJO(getApplication());
user = profilePojo.getProfile(1);

getProfile method will be used to retrieve information about the user. Once the application is started the first action will be looking into the database for information, in case it hasn't information, all Edit Texts will appear empty; otherwise, Edit Texts appear with information.

The logic described bellow is shown as follows.

if (user != null) {
    username.setText(user.getUsername());
    byte[] bitmapdata = user.getPhoto();
    Glide.with(this).load(byteArray2Bitmap(bitmapdata)).into(imageview);
    switch (user.getGender()) {
        case "male":
            male.setChecked(true);
            female.setChecked(false);
            break;
        case "female":
            female.setChecked(true);
            male.setChecked(false);
           break;
      }
      birthday.setText(parseDate(user.getBirthday()));
}

Now comes the insert or update logic when save button is pressed,

save.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        byte[] img;
        String gender;
        if (bitmap == null) {
            img = user.getPhoto();
        } else {
            img = convertBitmap2byte(bitmap);
        }

        if (female.isChecked()) {
            gender = "female";
        } else {
            gender = "male";
        }

        if (user == null) {
            user = new profileModel(
                        username.getText().toString(),
                        gender,
                        birthdate,
                        img);

            profilePojo.insert(user);
         } else {
             user.setGender(gender);
             user.setPhoto(img);
             user.setUsername(username.getText().toString());
             if (birthdate != null) {
                 user.setBirthday(birthdate);
             }
             profilePojo.update(user);
         }
     }
});

Before validating user emptiness, recollect data from main activity and set them into global variables. After that, create the user if it's empty and do insert operation, if it's not empty, do update operation.

Notice that we create two more method parseDate and convertBitmap2byte. The first one is used to convert a date variable into string.

private String parseDate(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int day = cal.get(Calendar.DAY_OF_MONTH);
    int month = cal.get(Calendar.MONTH);
    int year = cal.get(Calendar.YEAR);

    String sDay = String.valueOf(day);
    String sMonth = getMonth(month);
    String sYear = String.valueOf(year);

    sDay = addLeftZero(sDay);
    return (sMonth + " " + sDay + ", " + sYear);
}

The second one is used to convert a bitmap image into byte array to store it into database instead of creating new folder on gallery.

private Bitmap byteArray2Bitmap(byte[] bitmapdata) {
    return BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
}

Aaaand... that's it. Now we have a functional profile activity, the next post will be the last one of this series, checking a little bit of designing. I'm not really good at it, but I'll try my best to bring something interesting.

As always, the project can be forked on github for the purpose you want to give it.

Top comments (0)