Daniel Mohajer
Daniel Mohajer

Reputation: 139

How to make a Table with room library in android studio using Java?

I wanna try to make a table to hold 2 columns with Room Library in android studio with Java (not in Kotlin) .

The problem here, is that my data is something like this :

Year Dowry
1317 0.004
1318 0.004
1319 0.004
1320 0.008
1400 0.255

So for this i have made a Class named Data and i valued it like this :

    @Entity(tableName = "tbl_data")
public class Data {
    @PrimaryKey(autoGenerate = true)
    private long id;
    private int year;
    private int dowry;
 
    public Data(int year, int dowry) {
        this.year = year;
        this.dowry = dowry;
    }


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getDowry() {
        return dowry;
    }

    public void setDowry(int dowry) {
        this.dowry = dowry;
    }
}

and then i made a Database like this :

@Database(version = 1 , exportSchema = false , entities = {Data.class} )
public abstract class AppDatabase extends RoomDatabase   {
        private static AppDatabase appDatabase;


    public static AppDatabase getAppDatabase(Context context) {
            appDatabase= Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class,
                    "db_app")
                    .allowMainThreadQueries()
                    .build();
        return appDatabase;
    }

    public abstract DataDao getDataDao();

}

How to add does data into my data.class AKA "tbl_data" ?

Upvotes: 1

Views: 189

Answers (1)

MikeT
MikeT

Reputation: 57043

In the DataDao interface (or abstract class) that is annotated with @Dao you could have.

@Insert
long insert(Data data);

You can then insert individual rows e.g.

    db = AppDatabase.getAppDatabase(this);
    dao = db.getDataDao();
    dao.insert(new Data(1317,0004));
    dao.insert(new Data(1318,0004));
    dao.insert(new Data(1319,0004));

The result being (when first run):-

enter image description here

However

using int for the dowry doesn't cater for decimal numbers and hence the use of 0004 (which equates to 4).

As such you may wish to change private int dowry; to private double dowry; along with changing the code for the respective getters and setters.

Multiple/Mass Inserts

If you added (to DataDao) :-

@Insert
long[] insert(Data ... data);

Then you could do mass/multiple inserts such as :-

dao.insert(new Data(1317,0004), new Data(1318,0004),new Data(1319,0004));

The long or long[] is the id of the inserted row or rows (or -1 if the row was not inserted).

The following is an example of what could be done with mass inserts, including interrogating the results:-

    Data[] anotherArrayOfDatas = new Data[100];
    for (int i=0; i < 100; i++) {
        anotherArrayOfDatas[i] = new Data(1300 + i,0.004 + i);
    }
    long[] insertedIdList = dao.insert(anotherArrayOfDatas);
    long insertedOk =0;
    long notinserted = 0;
    for (int i = 0; i < insertedIdList.length; i++) {
        if (insertedIdList[i] < 0) {
            notinserted++;
        } else {
            insertedOk++;
        }
    }
    Log.d("INSERTED","Number of inserts was " + insertedOk + ". Number not inserted was " + notinserted);

After running the above, the Log includes :-

D/INSERTED: Number of inserts was 100. Number not inserted was 0

With data in the database looking like :-

enter image description here

As for handling the string {1317 | 0.004, 1318 | 0.004, 1319 | 0.004, 1320 | 0.008, ... 1400 | 0.255 } for input.

Then (assuming that ... is and so on) and thus removed then you need to:-

  1. strip off the leading and trailing curly brackets.
  2. split the remaining string into an array at each ,
  3. for each array split at the | removing the spaces and then
  4. create a Data object from the 2 parts
  5. the result should be an Array of Data's that can then be inserted.

As an example :-

First yes another dao has been added to mass insert using an ArrayList as per :-

@Insert
long[] insert(ArrayList<Data> dataArrayList);

The the following code was added :-

    String datain = "{1317 | 0.004, 1318 | 0.004, 1319 | 0.004, 1320 | 0.008,1400 | 0.255 }";
    ArrayList<Data> newDatas = new ArrayList<>();
    String x = datain.substring(1,datain.length() - 1);
    String[] split1 = x.split(",");
    for (String s: split1) {
        s = s.replace(" | ","~");
        String[] parts = s.split("~");
        if (parts.length == 2) {
            try {
                newDatas.add(new Data(Integer.parseInt(parts[0].trim()), Double.parseDouble(parts[1].trim())));
            }
            catch (Exception e) {
            }
        }
    }
    dao.insert(newDatas);

With the database now including :-

enter image description here

Upvotes: 1

Related Questions