Error with query in SugarORM - android

I'm trying to get number of rows in my Sugar database for each month. My DATE_INSERT is String value like dd-MM-yyyy. I'm trying to set query, but getting error:
android.database.sqlite.SQLiteException: near "LIKE": syntax error (code 1): , while compiling: SELECT * FROM EXERCISE_DATA WHERE DATE_INSERT LIKE
Here's my method. I'm trying to get list size for each month and draw it via GraphView:
private DataPoint[] generateYearlyData() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH,Calendar.JANUARY);
int monthIndex = 12;
DataPoint[] values = new DataPoint[monthIndex];
for (int i=0; i < monthIndex; i++) {
SimpleDateFormat sdf = new SimpleDateFormat("MM-yyyy");
String queryMonth = sdf.format(cal.getTime());
String completeArgs = new StringBuilder().append("'%").
append(queryMonth).append("%'").toString();
double x = i;
double y = (double) ExerciseData.findWithQuery(ExerciseData.class,
"SELECT * FROM EXERCISE_DATA WHERE DATE_INSERT LIKE",completeArgs).size();
DataPoint v = new DataPoint(x, y);
values[i] = v;
cal.add(Calendar.MONTH, 1);
}
return values;
}

The third parameter of findWithQuery is a parameter value, or a list of parameter values. These values are inserted into the query string at the places that are marked with a parameter marker.
Your query does not contain any parameter markers. You need to write ... LIKE ?.

Related

records inserted in a sqlite table are the same for each row

I have a JSONArray which contains many records. I want to compare a string inside those object with a similar(I know it has the same value) record in my SQLite db. but when I loop the table each row value has the first row value.
INSERT A RECORD TO DB >> it returns different value
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
JSONObject row = pagamenti.getJSONObject(i); /** LOOP OGGETTI */
String fattura = row.getString("Fattura");
String descrizione = row.getString("Descrizione");
String scadenza = row.getString("Data Scadenza");
String importo = row.getString("Importo");
String stato = row.getString("Stato Pagamento");
// FATURA SHOW ALL DIFFRERENtS VALUE CORRECTLY
fieldsNameTasse.add("fattura");
fieldsValueTasse.add(fattura);
Toast.makeText(getContext(), fattura.toString(), Toast.LENGTH_LONG).show();
fieldsNameTasse.add("descrizione");
fieldsValueTasse.add(descrizione);
fieldsNameTasse.add("scadenza");
fieldsValueTasse.add(scadenza);
fieldsNameTasse.add("importo");
fieldsValueTasse.add(importo);
fieldsNameTasse.add("stato");
fieldsValueTasse.add(stato);
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
CHECK DB ROW VALUE << it returns always the first value
/** SHOW ALWAYS THE SAME VALUE*/
int counter = 0;
Cursor cursor = DBmanager.readAll("TasseIncoming");
while(cursor.moveToNext()) {
String ffattura = cursor.getString(cursor.getColumnIndex("fattura"));
counter++;
Toast.makeText(getContext(), ffattura+" - "+counter, Toast.LENGTH_LONG).show();
}
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
for (int i = 0; i < pagamenti.length(); i++) {
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}
Every time you loop, you're just adding values to the end of what's already in those ArrayLists. So there's lots of duplicate column names with different values for each. Some quick testing:
sqlite> create table foo(a, b);
sqlite> insert into foo(a,b,a,b) values(1,2,3,4);
sqlite> select * from foo;
a b
---------- ----------
1 2
indicates that when a column is included multiple times in an INSERT, only the first corresponding value is used. Hence only ever getting the values from the first iteration of the loop.
The easy fix is to move those variable definitions inside the loop, so each insert is done with a fresh set of columns and values:
for (int i = 0; i < pagamenti.length(); i++) {
ArrayList<String> fieldsNameTasse = new ArrayList<String>();
ArrayList<String> fieldsValueTasse= new ArrayList<String>();
// add stuff to the above arraylists
DBmanager.insert("TasseIncoming", fieldsNameTasse, fieldsValueTasse);
}

Check from ArrayList in DB if equal

I have a table that store two variables Days and percent’s. I want to assign them to a specific variable. From the Database Helper class, I’m getting the last 7 entries:
//----------------Graping the last seven elements ----------------------------------//
public ArrayList<StatsitcsHelper> GetWeaklyPrograss() {
SQLiteDatabase db = this.getReadableDatabase ();
Cursor cursor = db.rawQuery ("select * from " + TABLE_PROGGRES, null);
ArrayList<StatsitcsHelper> datas = new ArrayList<>();
if (cursor != null) {
cursor.moveToFirst ();
for (int i = cursor.getCount () - 7 ; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
StatsitcsHelper data = new StatsitcsHelper();
data.WeakleyDate= cursor.getString(cursor.getColumnIndex(COL_P_Date));
data.WeakleyPercent = cursor.getInt (cursor.getColumnIndex(COL_P_Percentage));
datas.add(data);
cursor.moveToNext ();
}
cursor.close ();
}
return datas;
}
I want to build if statement that will say if day is Saturday then assign Saturday Percent Variable is Statistics Class to the percent associated from the database. Same goes for Sunday ….etc.
Inside the Statistics Class:
public void WeaklyStatstics(){
int saturday = 0,
sunday = 0,
monday = 0,
tuesday = 0,
wednsday = 0,
thersday = 0,
friday = 0;
StatsitcsHelper statsitcsHelper = new StatsitcsHelper ();
DatabaseHelper databaseHelper = new DatabaseHelper (getActivity ());
//---------------------TO DO----------------------------------------//
}}
I don’t know how to analysis each item from the list in the database to another class.
Here is the Insertion of the Table:
// ----------------Proggres Table ------------------------------------//
public boolean insertPrograss(String Date, Integer percentage) {
SQLiteDatabase db = this.getWritableDatabase ();
ContentValues contentValues = new ContentValues ();
contentValues.put (COL_P_Date, Date);
contentValues.put (COL_P_Percentage, percentage);
long result = db.insert (TABLE_PROGGRES, null, contentValues);
db.close ();
return result != -1;
}
the method is called by scheduler that will store the date into just day by using date formate, and the output will be Monday, 87.
i want to write a method to get the last 7 inputs through GetWeaklyPrograss method. and assign it to the variables something like this
if(statsitcsHelper.WeakleyDate.equals ("monday")){
saturday = statsitcsHelper.WeakleyPercent;
}
and here is the statsitcsHelper:
public class StatsitcsHelper {
//-------------- Weakly Progress -----------------------/
public String WeakleyDate;
public int WeakleyPercent;
}
can you try this logic ,
public void WeaklyStatstics(){
int saturday = 0,
sunday = 0,
monday = 0,
tuesday = 0,
wednsday = 0,
thersday = 0,
friday = 0;
//StatsitcsHelper statsitcsHelper = new StatsitcsHelper ();
DatabaseHelper databaseHelper = new DatabaseHelper (getActivity());
ArrayList<StatsitcsHelper> statsitcsHelperList = databaseHelper.GetWeaklyPrograss();
for (StatsitcsHelper statsitcsHelper : statsitcsHelperList)
{
if(statsitcsHelper.WeakleyDate.equals("Monday")){
monday = statsitcsHelper.WeakleyPercent;
}else if (statsitcsHelper.WeakleyDate.equals("Tuesday")){
tuesday = statsitcsHelper.WeakleyPercent;
}
//todo and write for other days too
}
// In here you can use all valid data
}
I am not sure I understand what the problem is.
However to check the day of week, you can get some ideas from this:
check if date() is monday? java
On a side note:
Your cursor contains all of the data in the table! It is usually better to get the results you want (last seven elements) on your cursor.
Limit your DB query, down to the interesting data. Instead of taking all data from the DB (select * from), you should specialize your query.
Look for SQL expressions ORDER BY, ASC, DESC, LIMIT, and you will get there.

Android - MPAndroidChart LineChart, not able to plot according to value date

I am using MPAndroidChart for my line chart.
I have date values and score values.
Example: on 11/10/2016 my score was 45.
I am struggling with the dates. Not sure how to set it in my setYAxisValues.
I am getting my values from a rest api and putting it in the graph.
This part is where i have my problem.
yVals.add(new Entry(Float.valueOf(ocd.getScore()), foo));
If I change foo to a normal int value like 1, 2, 3 I have no problem. The graph is working. The issue, i need to use dates to plot my value at the correct place.
#Override
protected void onPostExecute(List<ResultModel> result) {
super.onPostExecute(result);
//populating my yAxis with values from rest
for (ResultModel ocd : resModelList){
long unixSeconds = Long.parseLong(ocd.getPost_date());
Date date = new Date(unixSeconds*1000L);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = sdf.format(date);
int foo = Integer.parseInt(formattedDate);
yVals.add(new Entry(Float.valueOf(ocd.getScore()), foo));
}
}
The X axis is working
//set vales
private ArrayList<String> setXAxisValues(){
xVals = new ArrayList<String>();
//MM/dd/yyyy
xVals.add("01/01/2016");
xVals.add("02/01/2016");
xVals.add("03/01/2016");
xVals.add("04/01/2016");
xVals.add("05/01/2016");
return xVals;
}
private ArrayList<Entry> setYAxisValues(){
yVals = new ArrayList<Entry>();
return yVals;
}
Thanks in advance
I had the similar issue, the point is - MPChart library cannot have anything but float for X axis. I'd suggest you to have X axis represented by date's millis. Suppose you have four values with dates "01/01/2016", "02/01/2016", "03/01/2016", "04/01/2016", "05/01/2016". You add values like
yVals.add(new Entry(Float.valueOf(ocd.getScore()), "01/01/2016".toMillis()));
"01/01/2016".toMillis() is pseudocode of course, you need to convert your date to int (float).
Then, set up minX as "01/01/2016".toMillis(), maxX as"04/01/2016".toMillis(),
and provide a label formater which will format this millis back to string dates:
private class LabelFormatter implements AxisValueFormatter {
private Context context;
private LabelFormatter(Context context) {
this.context = context;
}
#Override
public int getDecimalDigits() {
return -1;
}
#Override
public String getFormattedValue(float value, AxisBase axis) {
return DateUtils.formatDateTime(context, (long) value, DateUtils.FORMAT_SHOW_DATE);
}
}

Android - Elements of List are getting replaced automatically

I have an empty list. I fill it with my class's instances in a loop. And right after adding an instance, I retrieve the last element and check its parameters. The values of parameters are fine.
Now, when I have filled all the values and control gets out of the loop, the date and time (which are instances of Calendar) of all the elements of that list are somehow replaced with the very last element's date and time, whereas the rest of parameters remain the same. I don't know if there is a logical error in my code or there is a bug in Android Studio.
I am printing out the values to Logcat, before entering the element and after entering that element. The values are same. But when the control reaches cursor.close(), all elements in that list are replaced.
public List<YearChart> readYearChart() throws Exception {
List<YearChart> yearChart = null;
SimpleDateFormat dateFormat = TheApplication.getDateFormat();
SimpleDateFormat timeFormat = TheApplication.getTimeFormat();
Cursor cursor = sqLiteDatabase.query(MyDatabaseHelper.table_YearChart, super.columnsToRetrieve, null, null, null, null, null);
if(cursor.moveToFirst()) {
yearChart = new ArrayList();
int id;
Calendar date = Calendar.getInstance();
int namazId;
Calendar time = Calendar.getInstance();
int i=0;
do
{
id = cursor.getInt(cursor.getColumnIndex(super.columnsToRetrieve[0]));
String dateStr = cursor.getString(cursor.getColumnIndex(super.columnsToRetrieve[1]));
namazId = cursor.getInt(cursor.getColumnIndex(super.columnsToRetrieve[2]));
String timeStr = cursor.getString(cursor.getColumnIndex(super.columnsToRetrieve[3]));
if(!dateStr.isEmpty() && !timeStr.isEmpty())
{
date.setTime(dateFormat.parse(dateStr));
time.setTime(timeFormat.parse(timeStr));
YearChart yc = new YearChart(id, date, namazId, time);
Log.v("YearChart_ID >", String.valueOf(yc.getId()));
Log.v("YearChart_Date>", TheApplication.getDateFormat().format(yc.getDate().getTime()));
Log.v("YearChart_NID >", String.valueOf(yc.getNamazId()));
Log.v("YearChart_Time>", TheApplication.getTimeFormat().format(yc.getTime().getTime()));
Log.v("*****", "*****");
yearChart.add(yc);
YearChart yc1 = yearChart.get(i);
Log.v("YearChart_ID >", String.valueOf(yc1.getId()));
Log.v("YearChart_Date>", TheApplication.getDateFormat().format(yc1.getDate().getTime()));
Log.v("YearChart_NID >", String.valueOf(yc1.getNamazId()));
Log.v("YearChart_Time>", TheApplication.getTimeFormat().format(yc1.getTime().getTime()));
Log.v("*****", "*****");
i++;
}
} while (cursor.moveToNext());
}
cursor.close();
return yearChart;
}
I am using Android Studio (v1.1.0).
You're passing the same reference to date and time - meaning each element in the list holds a reference to those exact objects. When you call date/time methods, you'll be updating those two variables which all your list items point to.
The solution is to move the instantiation of date and time into the do-while loop.

Array access producing unwanted result

I am getting an unusual result when attempting to place a value in an array.
I have an array table[] of a simple class result{ int score, long time, string ID}
Intention is to have a sort of leader board.
My code happily finds the correct place to insert a new score if it is in the top 10.
int ix = 0;
int jx = 10; //
while ( ix < jx )
{
if (points > sTable[ix].points)
{
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
}
ix++;
}
Problem is that when I try to insert the score using sTable[ix].score = score;
The value gets written to sTable[ix].score and also sTable[ix +1].score.
It is repeatable, it occurs at any value of ix, I have single stepped through the code and as far as I can tell the command only executes once.
Has anyone seen this before?
That because you copied the object reference to the next element in the array. You should copy the values, or create a new object:
Option A:
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx].time = sTable[jx -1].time;
sTable[jx].score = sTable[jx -1].score;
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
Option B:
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
sTable[ix] = new Result(score, time, ""); // Or however you construct the object

Categories

Resources