how to write a query with a where clause using greenDao - java

I am trying to write a simple query that contains a group by and a where clause in greendao however I am getting an error when I add in the where clause . Is there another way to write the where clause so that I can get this to work
I am basically getting the day part of today and subtracting 1 so that I can upload data from the previous day.
public List<AppTimeUsage> LoadAppTimeUsageData() {
List<AppTimeUsage> items = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
int thisDay = calendar.get(Calendar.DAY_OF_MONTH);
int previousDayCheck = thisDay -1 ;
String sqlWhere;
sqlWhere = "WHERE DAY_RECORDED = " + previousDayCheck;
String sql = "SELECT APP_NAME , SUM(APP_TIME_SPENT) , DAY_RECORDED FROM APP_TIME_USAGE " + sqlWhere + " GROUP BY APP_NAME ; ";
Cursor c = appTimeUsageDao.getDatabase().rawQuery(sql, null);
int offset = 0;
int d;
int cd;
String e = "";
while (c.moveToNext()) {
AppTimeUsage atu = new AppTimeUsage(
Long.MIN_VALUE,
new Date(),
c.getInt(1),
c.getString(0),
c.getInt(2)
// break;
);
items.add(atu);
//stats = atu;
}
return items;
}

Related

how to use a jCheckBox to execute one query if selected and another if not

I want to display some students fees track on a JFrame when a jbutton is clicked after typing the StudentID in a jTextField.
The student data is stored in MySQL Db, the table studentrolls contains info about the students with STRollID as Primary Key and StudentID, BachID as Foreign Key and the table fees contain all students fee record of past years and actual year with STRollID as Primary Key and BachID as Foreign Key.
I want to display after inserting the StudentID on a jTextField and clicking a jButton only actual year fee if a jCheckBoxonlythisyearfee is selected, otherwise, the frame will display all the fee record on a jTable and on some jLabels.
I wrote this code, I am not getting any error but when I run the file, I'm getting all the student fee records but when I'm clicking on the jCheckBoxonlythisyearfee nothing is happening am not getting only this year fee record.
Is there anything wrong with my code? Please help.
private void rSButtonIconDsearchstidActionPerformed(java.awt.event.ActionEvent evt) {
try {
Date d = new Date();
int year = d.getYear();
int currentYear = year + 1900;
boolean thisyrchecboxisSelected = jCheckBoxonlythisyearfee.isSelected();
String sqlquerystfeeslist;
if (thisyrchecboxisSelected) {
sqlquerystfeeslist = "SELECT * FROM studentrolls, fees WHERE studentrolls.StudentID = ? AND studentrolls.STRollID = fees.STRollID AND studentrolls.BachID = '"
+ currentYear + "' ORDER BY studentrolls.BachID";
} else {
sqlquerystfeeslist = "SELECT * FROM studentrolls, fees WHERE studentrolls.StudentID = ? AND studentrolls.STRollID = fees.STRollID ORDER BY studentrolls.BachID";
}
PreparedStatement preparedStatement = con.prepareStatement(sqlquerystfeeslist);
PreparedStatement pst = con.prepareStatement(sqlquerystfeeslist);
if (!jTextFieldsearchstid.getText().isEmpty()) {
preparedStatement.setString(1, jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
DefaultTableModel tblModelfee = (DefaultTableModel) jTablestfeeslist.getModel();
tblModelfee.setRowCount(0); // to clear the table before inserting new data
while (resultSet.next()) {
int stfeebalenceint;
int feecostint = Integer.parseInt(resultSet.getString("MontantFrais"));
int paidamountint = Integer.parseInt(resultSet.getString("MontantPayE"));
stfeebalenceint = feecostint - paidamountint;
String feestatus;
if (stfeebalenceint <= 0) {
feestatus = "SOLDE";
} else {
feestatus = "NO SOLDE";
}
String scolaryearfee = resultSet.getString("BachID");
String feetype = resultSet.getString("TypeFrais");
String feecost = String.valueOf(resultSet.getInt("MontantFrais"));
String paidamount = String.valueOf(resultSet.getInt("MontantPayE"));
String stfeebalence = String.valueOf(stfeebalenceint);
String stfeeslistTableData[] = {scolaryearfee, feetype, feecost, paidamount, stfeebalence, feestatus};
tblModelfee.addRow(stfeeslistTableData);
int stTotfeecost = 0;
for (int i = 0; i < jTablestfeeslist.getRowCount(); i++) {
stTotfeecost = stTotfeecost + Integer.parseInt(jTablestfeeslist.getValueAt(i, 2).toString());
}
int stTotpaidamount = 0;
for (int i = 0; i < jTablestfeeslist.getRowCount(); i++) {
stTotpaidamount = stTotpaidamount + Integer.parseInt(jTablestfeeslist.getValueAt(i, 3).toString());
}
int stTotfeebalence;
stTotfeebalence = stTotfeecost - stTotpaidamount;
String stTotfeestatus;
if (stTotfeebalence <= 0) {
stTotfeestatus = "SOLVABLE";
} else {
stTotfeestatus = "INSOLVABLE";
}
jLabelstTotfeecost.setText(Integer.toString(stTotfeecost));
jLabelstTotpaidamount.setText(Integer.toString(stTotpaidamount));
jLabelstTotfeebalence.setText(Integer.toString(stTotfeebalence));
jLabelstTotfeestatus.setText(stTotfeestatus);
}
} else {
JOptionPane.showMessageDialog(this, "Veillez taper le matricule d'un eleve svp.");
}
} catch (Exception exception) {
JOptionPane.showMessageDialog(this, "erreur des donnees: " + exception.getMessage());
}
}

Android SQLite querys are too slow

Good day guys. I have an query in my app which is called very often, and it takes lot of time. My db is encrypted with SQLiteCipher (I know that costs a lof of performance so I call and open DB only once). So actually i have a listview with a custom adapter which lists die name, lastMassage and the time of the lM. So I have to do this work:
public Massage getLastMassage(String ChatNumber) {
String[] args = {ChatNumber};
//String selectQuery="SELECT * FROM " + MassageDBHelper.DATABASE_NAME + " WHERE PhoneNumber=?";
//Cursor cursor=database.rawQuery(selectQuery,args);
Cursor cursor = database.query(MassageDBHelper.DATABASE_NAME, columns, "PhoneNumber=?", args, null, null, null);
cursor.moveToLast();
Massage massage = cursorToMassage(cursor);
cursor.close();
return massage;
}
That was the code in my databaseHelperClass called MassageDataSource, I've tried also the query string but there are not differences in Performance.
In my CustomAdapter I have to do this for every Chat (every person who was written):
Massage lastMassage = massageDataSource.getLastMassage(kontaktItem.getNummer());
Date date = lastMassage.getTimeAsDate();
cal.setTime(date);
int Jahr = cal.get(Calendar.YEAR);
int Monat = cal.get(Calendar.MONTH);
int Tag = cal.get(Calendar.DAY_OF_MONTH);
int Stunden = cal.get(Calendar.HOUR_OF_DAY);
int Minuten = cal.get(Calendar.MINUTE);
if (Jahr < Kalenderjahr || Monat < Kalendermonat || Tag + 1 < Kalendertag) {
viewHolder.Uhrzeit.setText(String.format("%02d", Tag) + "." + String.format("%02d", Monat) + "." + Jahr % 1000);
} else if (Tag < Kalendertag) {
viewHolder.Uhrzeit.setText(R.string.gestern);
} else {
viewHolder.Uhrzeit.setText(String.format("%02d", Stunden) + ":" + String.format("%02d", Minuten));
}
viewHolder.Kontaktname.setText(kontaktItem.getName());
viewHolder.Chatsnippet.setText(lastMassage.getMassageText());
//set Image from server
return view;
Edit Here is also the cursorToMassage function which is called:
private Massage cursorToMassage(Cursor cursor) {
int idPhoneNumber = cursor.getColumnIndex(MassageDBHelper.COLUMN_PHONENUMBER);
int idType = cursor.getColumnIndex(MassageDBHelper.COLUMN_TYPE);
int idMassagetext = cursor.getColumnIndex(MassageDBHelper.COLUMN_MASSAGETEXT);
int idAttachment = cursor.getColumnIndex(MassageDBHelper.COLUMN_ATTACHMENTID);
int idTime = cursor.getColumnIndex(MassageDBHelper.COLUMN_TIME);
int idPosition = cursor.getColumnIndex(MassageDBHelper.COLUMN_POSITION);
String phoneNumber = cursor.getString(idPhoneNumber);
String type = cursor.getString(idType);
String massagetext = cursor.getString(idMassagetext);
String attachment = cursor.getString(idAttachment);
String time = cursor.getString(idTime);
Boolean position = Boolean.valueOf(cursor.getString(idPosition));
Massage massage;
if (type.equals("text")) {
massage = new Massage(position, massagetext, phoneNumber, time);
} else {
massage = new Massage(position, attachment, type, phoneNumber, time);
}
return massage;
}
Try transaction.
Android Database Transaction
public Massage getLastMassage(String ChatNumber) {
database.beginTransaction();
Massage massage = null;
try {
String[] args = {ChatNumber};
//String selectQuery="SELECT * FROM " + MassageDBHelper.DATABASE_NAME + " WHERE PhoneNumber=?";
//Cursor cursor=database.rawQuery(selectQuery,args);
Cursor cursor = database.query(MassageDBHelper.DATABASE_NAME, columns, "PhoneNumber=?", args, null, null, null);
cursor.moveToLast();
massage = cursorToMassage(cursor);
cursor.close();
} catch {
//Error in between database transaction
} finally {
database.endTransaction();
return massage;
}
}

Android Create Calendar Event always as Birthday

I have a strange issue when I create a calendar event programmatically
its always noted as Birthday Calendar (type) I don't have any clue why its noted like that.
My code I use is as below: Xamarin C#
ContentResolver cr = ((Activity)Forms.Context).ContentResolver;
ContentValues values = new ContentValues();
String eventUriString = "content://com.android.calendar/events";
//Insert Events in the calendar...
values.Put(CalendarContract.Events.InterfaceConsts.CalendarId, 1);
values.Put(CalendarContract.Events.InterfaceConsts.Title, title);
values.Put(CalendarContract.Events.InterfaceConsts.Status, 1);
values.Put(CalendarContract.Events.InterfaceConsts.Description, description);
values.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(year, month, day, hour, minute));
values.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(year, month, day, hour, minute));
values.Put(CalendarContract.Events.InterfaceConsts.AllDay, allday ? "1" : "0");
values.Put(CalendarContract.Events.InterfaceConsts.HasAlarm, hasalarm ? "1" : "0");
values.Put(CalendarContract.Events.InterfaceConsts.EventColor, Android.Graphics.Color.Green);
values.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "GMT+" + zone + ":00");
values.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "GMT+" + zone + ":00");
cr.Insert(Android.Net.Uri.Parse(eventUriString), values);
Please does someone has any tips or ideas which can point me to the right direction?
Thanks in advance.
Some devices uses calendar id = 1 for birthdays but generally not. So to get the correct calendar id for particular device (corresponding to the email id configured with calendar app), use below code:
private int getCalendarId(Context context){
Cursor cursor = null;
ContentResolver contentResolver = context.getContentResolver();
Uri calendars = CalendarContract.Calendars.CONTENT_URI;
String[] EVENT_PROJECTION = new String[] {
CalendarContract.Calendars._ID, // 0
CalendarContract.Calendars.ACCOUNT_NAME, // 1
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, // 2
CalendarContract.Calendars.OWNER_ACCOUNT, // 3
CalendarContract.Calendars.IS_PRIMARY // 4
};
int PROJECTION_ID_INDEX = 0;
int PROJECTION_ACCOUNT_NAME_INDEX = 1;
int PROJECTION_DISPLAY_NAME_INDEX = 2;
int PROJECTION_OWNER_ACCOUNT_INDEX = 3;
int PROJECTION_VISIBLE = 4;
cursor = contentResolver.query(calendars, EVENT_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
String calName;
long calId = 0;
String visible;
do {
calName = cursor.getString(PROJECTION_DISPLAY_NAME_INDEX);
calId = cursor.getLong(PROJECTION_ID_INDEX);
visible = cursor.getString(PROJECTION_VISIBLE);
if(visible.equals("1")){
return (int)calId;
}
Log.e("Calendar Id : ", "" + calId + " : " + calName + " : " + visible);
} while (cursor.moveToNext());
return (int)calId;
}
return 1;
}
Point to note : IS_PRIMARY_COLOUM which returns 1 in case of email id and not for bithdays and holidays.
Please refer: https://developer.android.com/reference/android/provider/CalendarContract.CalendarColumns.html#IS_PRIMARY for details.
Pkosta is pointing in the right direction.
You have to take the first calendar that is both VISIBLE and IS_PRIMARY.
long calId = 0;
String selection = CalendarContract.Calendars.VISIBLE + " = 1 AND "
+ CalendarContract.Calendars.IS_PRIMARY + " = 1";
Uri calendarUri = CalendarContract.Calendars.CONTENT_URI;
Cursor cur = cr.query(calendarUri, null, selection, null, null);
if (cur != null && cur.moveToFirst()) {
Get the field values
calID = cur.getLong(CalendarContract.Calendars._ID);
}
if (cur != null) {
cur.close();
}
return calId;
The question answered below is old please refer to Pkosta's answer which provides more accurate answer ...
You have to put CalendarId value as 3 instead of 1 which is default birthday calendar.
e.g.
values.Put(CalendarContract.Events.InterfaceConsts.CalendarId, 1);
change it to
values.Put(CalendarContract.Events.InterfaceConsts.CalendarId, 3);
It solved the same issue for me.

Unable to loop for different data

I am unable to loop through my database for timeList to output different time that I require. They only loop through the first one and display the same data for every output that I require. If I were to close the for loop of of the conversion, I would have problem displaying it in the output statement.
String[] timeMinute = timeList .split("<SPLIT>");
for (int t = 0; t <timeMinute.length; t ++)
{
String strDate = timeList;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date getDate = sdf.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(getDate);
int noOfHours = calendar.get(Calendar.HOUR_OF_DAY);
int noOfMinutes = calendar.get(Calendar.MINUTE);
int totalMinutes = noOfHours * 60 + noOfMinutes;
while ( rs.next() )
{
String RTD= rs.getString("RTD");
if ( !trd1.contains( RTD) )
trd1.add(RTD);
String admissionCOUNT = "";
if ( rs.getString("jae") != null )
admission = rs.getString("jae");
String[] admissionCOUNT = admission.split("<SPLIT>");
for ( int i = 0 ; i <gateNo.length ; i ++ )
{
if ( kpm.containsKey(gateNo[i]) )
kpm.get(admissionCOUNT [i]).put(RTD, + totalMinutes);
}
}
for ( int i = 0 ; i < .size(); i++)
{
stringWriter.append( trd1.get(i) + ",");
for ( String admissionCOUNT : kpm.keySet() )
{
if ( kpm.get(admissionCOUNT ).containsKey(trd1.get(i) ) )
MSO.get(admissionCOUNT ).append(totalMinutes +",");
else
MSO.get(admissionCOUNT ).append("0,");
}
}
The current output example -
data1,0,56,0
data2,56,0,0
data3,56,0,0
data4,0,0,56
Desire output example -
data1,0,87,0
data2,56,0,0
data3,43,0,0
data4,0,0,91
edit:
for ( String egm : .keySet() )
resultString += System.getProperty("line.separator") + gate + "," + MSO.get(egm).toString();

Getting SQLite DB data in 2d array and returning in android

I have the below function which I use to query the SQLite Db, put the retrieved records in to an array and return it back.
public String[][] getrecords(){
Log.i("SENDSERVER", "Get Records Called");
SQLiteDatabase sampleDB = this.getReadableDatabase();
Cursor c = sampleDB.rawQuery("SELECT id,welawa,lati,longi FROM " +
TABLE_LOCATIONS + " LIMIT 5", null);
String[][] aryDB = new String[5][4];
int i = 0;
if (c != null ) {
if (c.moveToFirst()) {
do {
String db_id = c.getString(c.getColumnIndex("id"));
String welawa = c.getString(c.getColumnIndex("welawa"));
String latitude = c.getString(c.getColumnIndex("lati"));
String longitude = c.getString(c.getColumnIndex("longi"));
aryDB[i][0] = db_id;
aryDB[i][1] = welawa;
aryDB[i][2] = latitude;
aryDB[i][3] = longitude;
Log.i("SENDSERVER", "Record Added"); //This doesn't get logged
i++;
}while (c.moveToNext());
}
}
Log.i("SENDSERVER", "Return Records");
return aryDB;
}
I try to retrieve the records and use them as below from my service class.
String aryDB[][] = dbh.getrecords();
Log.i("SENDSERVER", "GET DB RECORDS");
int i = 0;
int id = 0;
String welawa = "";
String lati = "";
String longi = "";
while(i < 5){
id = Integer.parseInt(aryDB[i][0]);
welawa = aryDB[i][1];
lati = aryDB[i][2];
longi = aryDB[i][3];
Log.i("SENDSERVERDB", id + " - " + welawa + " - " + lati + " - " + longi);
i++;
}
For some reason the array is not being returned.
My possible guesses are,
1. The defining of the function is wrong. My intention is to return the array.
2. I am getting the db connection / my retrieval code is wrong.
3. Some thing else that my noob brain can't comprehend.
Your help is greatly appreciated guys.
------EDIT
After adding some more logs the app crashes at
Cursor c = sampleDB.rawQuery("SELECT id,welawa,lati,longi FROM " +
TABLE_LOCATIONS + " LIMIT 5", null);
Any issue in my query?
It was a DB issue. Wrong ColumnName used.
The Cursor never returns null when there is no row which the requested conditions, just return a empty Cursor.
You code still has problem when the rawQuery returns 0 rows, cursor won't be null and do while loop will execute at least once.
So there will be problem on this line when the cursor is empty
c.getString(c.getColumnIndex("id"));
Change your code to this:
c.moveToFirst();
while (c.moveToNext())
{
String db_id = c.getString(c.getColumnIndex("id"));
String welawa = c.getString(c.getColumnIndex("welawa"));
String latitude = c.getString(c.getColumnIndex("lati"));
String longitude = c.getString(c.getColumnIndex("longi"));
aryDB[i][0] = db_id;
aryDB[i][1] = welawa;
aryDB[i][2] = latitude;
aryDB[i][3] = longitude;
Log.i("SENDSERVER", "Record Added"); //This doesn't get logged
i++;
}

Categories

Resources