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" ?
CodePudding user response:
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):-
- Database viewed using Android Studio's
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:-
- strip off the leading and trailing curly brackets.
- split the remaining string into an array at each
,
- for each array split at the | removing the spaces and then
- create a Data object from the 2 parts
- 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 :-