SQLite execute query and get result - android

I have that query
String queryMonthSize = "SELECT (julianday(Date('now')) -
julianday(date('now','-1 month')) FROM "+ TABLE_STATISTICS;
Which on sqlite it will return me the difference of the two dates.
How can i execute it on the android code so that i will return me the numerical value of the string?

Your implementation will be
queryMonthSizeIntValue = Integer.parseInt(queryMonthSize);
See the the static parseInt() method:
http://developer.android.com/reference/java/lang/Integer.html

Related

How do I perform a Room DAO multi table join #Query using select fields?

My Problem:
I'm struggling to eliminate the compiling error on the following Room #Query statement in a Room DAO. As you can see, the SQLite query statement is joining various fields from different tables. The missing fields identified by the error are a part of the Notes class constructor identified in the List type for the method. I think I need to change the List type identified. If I'm right, I need some guidance/suggestion on how I should resolve it. Do I need to create a new Class and DAO with just those specific fields queried? Or maybe just a class since there is not table specific to these fields only. The error is:
error: The columns returned by the query does not have the fields [commentID,questionID,quoteID,termID,topicID,deleted] in com.mistywillow.researchdb.database.entities.Notes even though they are annotated as non-null or primitive. Columns returned by the query: [NoteID,SourceID,SourceType,Title,Summary]
List getNotesOnTopic(String topic);
#Query("SELECT n.NoteID, s.SourceID, s.SourceType, s.Title, c.Summary FROM Comments as c " +
"LEFT JOIN Notes as n ON n.CommentID = c.CommentID " +
"LEFT JOIN Sources as s ON n.SourceID = s.SourceID " +
"LEFT JOIN Topics as t ON n.TopicID = t.TopicID WHERE t.Topic = :topic AND n.Deleted = 0")
List<Notes> getNotesOnTopic(String topic);
What I'm trying to do:
I'm attempting to convert and existing Java desktop app with an embedded an SQLite database. The above query does work fine in that app. I only want to pass field data from these tables.
What I've tried:
I've done some googling and visited some forums for the last few days (e.g. Android Forum, Developer.Android.com) but most of the Room #Query examples are single table full field queries (e.g. "Select * From table"). Nothing I found yet (there is probably something) quite addresses how and what to do if you are joining and querying only specific fields across tables.
I think I may have fixed my issue. I just created a new class called SourceTable and designated the queried fields in the constructor. The only catch was I, according to a follow up error, was that the parameters had to match the field names.
public class SourcesTable {
private int NoteID;
private int SourceID;
private String SourceType;
private String Title;
private String Summary;
public SourcesTable(int NoteID, int SourceID, String SourceType, String Title, String Summary){
this.NoteID = NoteID;
this.SourceID = SourceID;
this.SourceType = SourceType;
this.Title = Title;
this.Summary = Summary;
}
}
and then I update my list method:
List<SourcesTable> getNotesOnTopic(String topic);

Select multipile column through Room liberary

I want to select multiple column from SqLite through Room Library in Android SDK environment.
Below is the query for selecting it.
#Query("SELECT ID,message,timestamp FROM Chat_Message WHERE groupID =:groupID
ORDER BY timestamp DESC LIMIT 1")
public List get_last_msg_ID_timestamp (String
groupID);
My Last_Msg_Detail class which is define under main class is as follows:-
public class Last_Msg_Detail {
public Integer ID;
public String message;
public Long timestamp;
}
For accessing this three variable have created below method :-
Last_Msg_Detail last_record_t = new Last_Msg_Detail();
public Last_Msg_Detail get_last_msgand_time_stamp(String groupID){
List<Last_Msg_Detail> last_record =
chat_messageDao.get_last_msg_ID_timestamp(groupID);
last_record_t = last_record.get(0);
return last_record_t;
}
On Rebuilding Project, getting follow error
1. error: Cannot figure out how to save this field into database. You can
consider adding a type converter for it.
2. error: Not sure how to convert a Cursor to this method's return type
Kindly advise how to resolve.
Thanks in advance for your help.
your method return custom object and the object has a lot of fields.
so, when you try to return specific columns, you try to return a new object. so the error occurs.
to solve the problem, create a new object for the selected columns. it has to has these fields.
ID,message,timestamp
and use the object in your method
#Query("SELECT ID,message,timestamp FROM Chat_Message WHERE groupID =:groupID ORDER BY timestamp DESC LIMIT 1")
public List<NEW_OBJECT> get_last_msg_ID_timestamp (String groupID);

moveToFirst does not work

I am using moveToFirst and it works very well. But this sql query doesnt work. I don't know why. I didn't receive any error.
My query
String sqlKomut = "SELECT SHareket.*,CHareket.[Meblag],Cari.AnlikBakiye FROM CHareket , SHareket,Cari WHERE CHareket.[CariID]=SHareket.[CariID]=Cari.[CariID]= '"+cari.getCariID()+"' AND SHareket.[Seri]='"+hareket.getSeri()+"' AND SHareket.[Sira]='"+hareket.getSira()+"'AND SHareket.[Tip]='"+hareket.getTip()+"' AND SHareket.[Cins]='"+hareket.getCins()+"' ORDER BY SHareket.[Satir]";
and I get my cursor getValue here:
Cursor cursor = db.rawQuery(sqlKomut, null);
if(cursor !=null){
if(cursor.moveToFirst()){
do {
eleman.setStrEleman(cursor.getString(cursor.getColumnIndex("Seri")));
eleman.setIntEleman1(cursor.getInt(cursor.getColumnIndex("Sira")));
eleman.setIntEleman2(cursor.getInt(cursor.getColumnIndex("CariID")));
eleman.setIntEleman10(cursor.getInt(cursor.getColumnIndex("Cins")));
eleman.setIntEleman11(cursor.getInt(cursor.getColumnIndex("Tip")));
eleman.setIntEleman11(cursor.getInt(cursor.getColumnIndex("Satir")));
eklenenfaturalar.add(eleman);
} while (cursor.moveToNext());
}
}
WHERE CHareket.[CariID]=SHareket.[CariID]=Cari.[CariID]= '...'
You cannot do multiple comparisons in a single expression like that.
(The comparison returns a boolean value, 0 or 1; any more comparisons will then use this boolean instead of an ID value, e.g., you end up with something like 1=Cari.CariID.)
To use multiple comparisons, connect them with AND (as you already did with the other ones):
WHERE CHareket.[CariID]=SHareket.[CariID]
AND SHareket.[CariID]=Cari.[CariID]
AND Cari.[CariID]='...'
...

SQL MAX-MIN in ORMLITE - ANDROID

I want to know how can i use MAX MIN command with ORMLITE.
For example lets say we have this table
Table Name = Example
Column 1 = id
Column 2 = name
In ORMLITE how can i get max id ? I looked here but i didnt't understand exactly..
Can someone show me example about Max min in ORMLITE ?
QueryBuilder<Account, Integer> qb = accountDao.queryBuilder();
qb.selectRaw("MIN(orderCount)", "MAX(orderCount)");
// the results will contain 2 string values for the min and max
results = accountDao.queryRaw(qb.prepareStatementString());
String[] values = results.getFirstResult();
I found this from documentation
This is how I query for max ID in my code:
QueryBuilder<Example, String> builder = dao.queryBuilder();
builder.orderBy("id", false); // true or false for ascending so change to true to get min id
Example example = dao.queryForFirst(builder.prepare());
String id = null;
if (example == null)
id = "-1";
else
id = example.getId();
A couple of alternative answers can also be found here:
ORMLite - return item w/ maximum ID (or value)
You can use:
dao.queryRawValue("select MAX(columnName) from tableName")
It will directly return long value.
refer: http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_5.html#DAO-Methods
queryRawValue(String query, String... arguments)
Perform a raw query that returns a single value (usually an aggregate function like MAX or COUNT). If the query does not return a single long value then it will throw a SQLException.

assign database value for variable in android

This is about Android and SQLite database.
Simply, I want to know, how can I assign value to variable that get from the Database table?
I have table called wish and colmns are date[date value string], phoneno[phone no string] and wishtype[simply a string].
All I want is get phoneno, and wishtype according to usergiven date[input to the query will be the date] and assign those two into seperate variable.
I tried out so many methods, but it gives me a runtime errors.
String phone_no;
String wish_type;
Cursor c = getContentResolver().query(your_table_uri,
new String[] {"_id", "phone_no", "wish_type", "date" /*these are your column names*/},
"date=?", your_date_filter, null);
if(c.moveToFirst()) { // checks if c retrieves anything. you may want to check first if c!=null
phone_no = c.getString(c.getColumnIndex("phone_no"));
wish_type = c.getString(c.getColumnIndex("wish_type"));
}

Categories

Resources