I am using SQLite to store my information. I am storing the date as string format. Now I want to fetch the data based on the date, there might be more than one data for a single date. I have checked relevant questions and tried in my way but can not find the solution. Though I was able to get info of a single data for a particular date.
My code for fetching data from the database:
public ArrayList<ExpenseModel> getSingleExpenseDetails(String date){
SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();
String query = "select * from " + TABLE_SAVE_EXPENSE + " where "+ COLUMN_EXPENSE_DATE+ " = '" + date+ "'";
Cursor cursor=sqLiteDatabase.rawQuery(query, null);
ExpenseModel expenseModel=new ExpenseModel();
ArrayList<ExpenseModel> expenseModels = new ArrayList<>();
Log.v("Title : ",""+title);
if (cursor.moveToFirst()){
do {
expenseModel.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModel.setDescription(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DESCRIPTION)));
expenseModel.setAmount(cursor.getInt(cursor.getColumnIndex(COLUMN_EXPENSE_AMOUNT)));
expenseModel.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DATE)));
expenseModel.setCurrency(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_CURRENCY)));
Log.v("Info : ",""+cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModels.add(expenseModel)
}while (cursor.moveToNext());
}
cursor.close();
sqLiteDatabase.close();
return expenseModels;
}
ExpenseModel class:
package app.shakil.com.dailyexpense.Models;
public class ExpenseModel {
private int id;
private String title;
private String description;
private String date;
private int amount;
private String currency;
public ExpenseModel(){
}
public ExpenseModel(String title,String description,String date,int amount,String currency){
this.title=title;
this.description=description;
this.date=date;
this.amount=amount;
this.currency=currency;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
One obvious mistake that you do in your code is that you initialize expenseModel before the loop and use it inside the loop for all the rows:
ExpenseModel expenseModel=new ExpenseModel();
Move that line inside the loop:
do {
ExpenseModel expenseModel=new ExpenseModel();
expenseModel.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModel.setDescription(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DESCRIPTION)));
expenseModel.setAmount(cursor.getInt(cursor.getColumnIndex(COLUMN_EXPENSE_AMOUNT)));
expenseModel.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_DATE)));
expenseModel.setCurrency(cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_CURRENCY)));
Log.v("Info : ",""+cursor.getString(cursor.getColumnIndex(COLUMN_EXPENSE_TITLE)));
expenseModels.add(expenseModel)
}while (cursor.moveToNext());
Related
I'm trying to sort an Array by Collections.sort because SDK<24 but it's doing nothing, the array is in the same order, this is the code of my Comparator:
public class ComparatorFecha implements Comparator<Dinero> {
#Override
public int compare(Dinero o1, Dinero o2) {
return o1.getFecha().compareTo(o2.getFecha());
}
}
Here is the class Dinero:
public class Dinero implements Serializable {
private String nombre;
private String descripcion;
private int total;
private String date;
private String id;
private Date fecha;
public Dinero(String nombre, String descripcion, int total, String date) {
this.nombre = nombre;
this.descripcion = descripcion;
this.total = total;
this.date = date;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getFecha() {
return date;
}
public void setFecha(String fecha) {
this.date = fecha;
}
public Date stringToDate(String d1){
try {
Log.d(TAG, "FECHA CAMBIADA");
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(d1);
return date1;
} catch (ParseException e) {
Log.w(TAG, "FECHA NO CAMBIADA");
e.printStackTrace();
return null;
}
}
}
And finally here is which is supposed to sort:
public void getIngresos(String user, IngresosIsLoaded iLoaded){
final ArrayList<Dinero> beneficio = new ArrayList<>();
final IngresosIsLoaded ingresosIsLoaded = iLoaded;
DatabaseReference ref = database.getReference().child("Users").child(user).child("Ingresos");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
beneficio.clear();
for(DataSnapshot ds : dataSnapshot.getChildren()){
String nombreAux = ds.child("nombre").getValue().toString();
String descAux = ds.child("descripcion").getValue().toString();
String fecha = ds.child("fecha").getValue().toString();
int precioAux = Integer.parseInt(ds.child("total").getValue().toString());
dinero.setFecha(dinero.stringToDate(fecha));
dinero.setId(ds.getKey());
gastos.add(dinero);
}
Collections.sort(gastos, new ComparatorFecha());
gastosLoaded.gastosIsLoaded(gastos);
My array is not getting sorting, dont know why, also, there is no log of the class stringToDate, like is not making the function, maybe this could be the problem if "fecha" doesnt exists, nothing will be sorted.
Thanks!
Since your fecha field is not initialized in constructor, it will be null until you call setFecha(). To deal with null values in the sort, change your sort line as follows:
Collections.sort(gastos, Comparator.nullsFirst(new ComparatorFecha()));
In my Spring boot application, I have collection of Todos and a collection of Courses. In the view of the application, I return the collection of courses and display whatever course I need. The Todos are stored as 1 list which represents all the current Todos. What I would like to do is return a list of Todos for each course. So when the view is opened, the application would display the the course plus the individual todo list for that course.
Is there a way I can use the existing code to incorporate the new functionality. I have created the front end logic and would like to keep that. My initial idea was to add the the course id to the Todo.java, but that did not work.
Todo.java
#Document(collection="todos")
public class Todo {
#Id
private String id;
#NotBlank
#Size(max=250)
#Indexed(unique=true)
private String title;
private Boolean completed = false;
private Date createdAt = new Date();
public Todo() {
super();
}
public Todo(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return String.format(
"Todo[id=%s, title='%s', completed='%s']",
id, title, completed);
}
}
TodoRepository.java
#Repository
public interface TodoRepository extends MongoRepository<Todo, String> {
public List<Todo> findAll();
public Todo findOne(String id);
public Todo save(Todo todo);
public void delete(Todo todo);
}
Courses
#Document(collection = "courses")
public class Courses {
#Id
private String id;
private String name;
private String lecturer;
private String picture;
private String video;
private String description;
private String enroled;
public Courses(){}
public Courses(String name, String lecturer, String picture, String video, String description,String enroled) {
this.name = name;
this.lecturer = lecturer;
this.picture = picture;
this.video = video;
this.description = description;
this.enroled = enroled;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLecturer() {
return lecturer;
}
public void setLecturer(String lecturer) {
this.lecturer = lecturer;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnroled() {
return enroled;
}
public void setEnroled(String enroled) {
this.enroled = enroled;
}
#Override
public String toString() {
return "Courses{" +
"id='" + id + "'" +
", name='" + name + "'" +
", lecturer='" + lecturer + "'" +
", description='" + description + "'" +
'}';
}
}
I'm having a problem fetching data from database.
I'm trying to fetch the list of array.
But my problem is that i can only get the last element of the array maybe because it overwrites the previous one.
Here's my code.
String sql;
sql = "select * from NM_PROPERTIES_LOADER";
ResultSet rs = stmt.executeQuery(sql);
String prop_name = null;
String prop_value = null;
PropertyData reader = new PropertyData();
while(rs.next()){
prop_name = rs.getString("prop_name");
prop_value = rs.getString("prop_value");
reader.setPropName(prop_name);
reader.setPropValue(prop_value);
..//other setter..
System.out.println(prop_name + " " + prop_value);
}
prop.add(reader);
In my sysout I can retrieve all the datas. but on my page only the last element is retrieved. Here's my dao class.
public class PropertyData {
private int id;
private String propName;
private String propValue;
private String engineName;
private String desc;
private Date createdAt;
private String createdBy;
private Date updatedAt;
private String updatedBy;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPropName() {
return propName;
}
public void setPropName(String propName) {
this.propName = propName;
}
public String getPropValue() {
return propValue;
}
public void setPropValue(String propValue) {
this.propValue = propValue;
}
public String getEngineName() {
return engineName;
}
public void setEngineName(String engineName) {
this.engineName = engineName;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
In every iteration of the loop, you overwrite the content of reader.
You want to create reader inside the loop, not outside,
and also do prop.add(reader) inside the loop, not outside.
Like this:
String sql = "select * from NM_PROPERTIES_LOADER";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
PropertyData reader = new PropertyData();
String name = rs.getString("prop_name");
String value = rs.getString("prop_value");
reader.setPropName(name);
reader.setPropValue(value);
// other setter calls..
prop.add(reader);
}
I have a json string:
{
"Id": 1,
"Title": "A night with king of France",
"Description": "King's of France awesome audition",
"Day": "Monday",
"Time": "00:00:00",
"FinnishTime": "02:00:00",
"Picture": "http://cp91279.biography.com/1000509261001/1000509261001_1134394072001_Bio-Biography-Louis-XIV-LF-retry.jpg",
"Host1": {
"Id": 1,
"Name": "Louis XIV",
"Description": "The king of France - likes classical music"
}}
and I'm trying to deserialize it using json
Type listType = new TypeToken<Program>() {}.getType();
Program h = new Gson().fromJson(text, listType);
My Program Class looks like this:
private int Id;
private String Title;
private String Description;
private String Day;
private LocalTime Time;
private LocalTime FinnishTime;
private String Picture;
private Host Host1;
Program(int id, String title, String description, Host host, String day, LocalTime startTime, LocalTime finnishTime, String picture)
{
this.Id = id;
this.Title = title;
this.Description = description;
this.Day = day;
this.Time = startTime;
this.FinnishTime = finnishTime;
this.Picture = picture;
this.Host1 = host;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public Host getHost1() {
return Host1;
}
public void setHost1(Host host1) {
Host1 = host1;
}
public String toString() {
return this.Id + ". " + this.Title;
}
public String getDay() {
return Day;
}
public void setDay(String day) {
Day = day;
}
public LocalTime getTime() {
return Time;
}
public void setTime(LocalTime time) {
Time = time;
}
public LocalTime getFinnishTime() {
return FinnishTime;
}
public void setFinnishTime(LocalTime finnishTime) {
FinnishTime = finnishTime;
}
public String getPicture() {
return Picture;
}
public void setPicture(String picture) {
Picture = picture;
EDIT
private int Id;
private String Name;
private String Description;
public Host(int Id, String Name, String Description)
{
this.Id = Id;
this.Name = Name;
this.Description = Description;
}
public int getId() {
return Id;
}
public void setId(int id) {
this.Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
this.Description = description;
}
The error is Expected BEGIN_OBJECT but was STRING at line 1 column 120
I think that the problem is that it confuses Host1 variable with one of the others - but I have no idea why, and how to make it understand in correct way. What does line 1 column 120 mean?
You have to use a custom Type Adapter!
Try in this way:
JsonDeserializer<LocalTime> localTimeDeserializer = new JsonDeserializer<LocalTime>() {
#Override
public LocalTime deserialize(JsonElement jsonElem, Type type,
JsonDeserializationContext context) throws JsonParseException {
if (jsonElem == null) {
return null;
}
String localTimeStr = jsonElem.getAsString();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime localTime = LocalTime.parse(localTimeStr, formatter);
return localTime;
}
};
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalTime.class, localTimeDeserializer).create();
Type listType = new TypeToken<Program>() {}.getType();
Program program = gson.fromJson(json, listType);
line 1 column 120 is "Time": "00:00:00", you should use String for Time and FinnishTime
Trying to figure out how to use hibernate to call to get a list of the movies for a given genre?!
I tried getting a given genre then using the method from GenreDTO to get the set of movies.
Query hqlQuery = session.createQuery("FROM GenreDTO WHERE genre like :genre");
GenreDTO g = hqlQuery.setParameter("title","%" + term + "%").uniqueResult();
return g.getMovies();
Is there a better way?
CREATE TABLE Movie (
id INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
title VARCHAR(255),
poster VARCHAR(255),
director VARCHAR(255),
actors VARCHAR(255),
synopsis VARCHAR(3000),
release_date TIMESTAMP
);
CREATE TABLE Genre(
id INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
genre VARCHAR(255)
);
CREATE TABLE MovieHasGenre(
movie_id INTEGER REFERENCES Movie (id) NOT NULL,
genre_id INTEGER REFERENCES Genre (id) NOT NULL,
PRIMARY KEY (movie_id, genre_id)
);
package edu.unsw.comp9321.jdbc;
import java.util.HashSet;
import java.util.Set;
public class GenreDTO {
public GenreDTO() {}
public GenreDTO(int id, String genre) {
super();
this.id = id;
this.genre = genre;
}
private int id;
private String genre;
private Set<MovieDTO> movies = new HashSet<MovieDTO>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public Set<MovieDTO> getMovies() {
return movies;
}
public void setMovies(Set<MovieDTO> movies) {
this.movies = movies;
}
}
package edu.unsw.comp9321.jdbc;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.OneToMany;
public class MovieDTO implements Comparable {
private int id;
private String title;
private String poster;
private String director;
private String actors;
private String synopsis;
private String release_date;
private int cinema_id;
private Set<GenreDTO> genres = new HashSet<GenreDTO>();
private Set<ReviewDTO> reviews = new HashSet<ReviewDTO>();
private double rating;
public MovieDTO() {
}
public MovieDTO(int id, String title, String poster, String director,
String actors, String synopsis, String release_date, double rating) {
super();
this.id = id;
this.title = title;
this.poster = poster;
this.director = director;
this.actors = actors;
this.synopsis = synopsis;
this.release_date = release_date;
this.rating = rating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActors() {
return actors;
}
public void setActors(String actors) {
this.actors = actors;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public Set<GenreDTO> getGenres() {
return genres;
}
public void setGenres(Set<GenreDTO> genres) {
this.genres = genres;
}
public Set<ReviewDTO> getReviews() {
return reviews;
}
public void setReviews(Set<ReviewDTO> reviews) {
this.reviews = reviews;
}
public int getCinema_id() {
return cinema_id;
}
public void setCinema_id(int cinema_id) {
this.cinema_id = cinema_id;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
#Override
public int compareTo(Object o) {
MovieDTO other = (MovieDTO) o;
if (this.rating > other.rating) return -1;
if (this.rating < other.rating) return 1;
return 0;
}
}
Yes. There is a better way. Just use a join:
select m from Movie m join m.genres g where g.genre like :genre
or
select m from Genre g join g.movies m where g.genre like :genre
Note that using a like clause is a bit odd. You should use the ID of the genre to uniquely identify it. And if you only have part of a genre's name, you shouldn't assume only one genre contains this genre part.
Also, a DTO is not an entity, and vice-versa. Don't name an entity GenreDTO or MovieDTO. Name it Genre or Movie.