Check from ArrayList in DB if equal - android

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.

Related

Constantly retrieve data from database in a infinite loop

I created a database with a table named flagTable, this table only has two fields, which are id(auto increment) and an integer field. Next, in my program, I have a button that will trigger a thread to start. When the thread is starting, it constantly retrieve data from database, and check for the for the value, if the value is equal to one then it will trigger another new Thread, something like this:
private class statusOfStrummingInAnotherDevice extends Thread {
int value;
public void run() {
try{
while(true){
try{
if(flagCursor == null){
flagCursor = cdb1.getFlagAll();
}
}catch(Exception e){break;}
try{
Log.i("MAIN3ACTIVITY","getting status");
int size = cdb1.getSize(flagCursor);
Log.i("MAIN3ACTIVITY","SIZE is" + String.valueOf(xyz));
for(int i = 0 ; i < size ; i++){
flagCursor.moveToPosition(i);
Log.i("MAIN3ACTIVITY","getting status jkasdfasdf");
value = cdb1.getFlag();
if(value == 1){
Log.i("FLAGCURSOR=====>>>>","Succesful");
releasingNotes = new ReleasingNotes(IntendedChord);
releasingNotes.start();
//break;
}
cdb1.updateFlag(0);
Log.i("FLAGCURSOR=====>>>>",String.valueOf(value));
}
flagCursor = null;
}catch(Exception e){break;}
Log.i("MAIN3ACTIVITY","thread is sleeping");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}catch(Exception e){
}
}
}
In the meantime, the data that were retrieved from the database is using this function:
public Cursor getFlagAll(){
return getReadableDatabase().rawQuery(
"SELECT _ID, flag from flagTable", null);
}
And, the data that were updated to the database through this method:
public int updateFlag(int i) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("flag",i);
return db.update("flagTable" , contentValues , "_ID" + "= ?",new String[]{String.valueOf(1)});
}
Now, above codes will give no error, however, the data that were retrieved from the database is always 1, it keeps trigger a new function. In my above codes, I stated if the value is equal to 1, then the current thread will trigger a new thread to start, When its finished, the program will update the current data to 0. So that, the next round of the infinite loop can stop triggering new thread until a the conditon is met. What is problem overhere? did my codes really updated the new value? or I need to referesh the database every time I updated a new value.
Use Listeners to your database.
use SQLiteTransactionListener and do your things in onCommit()
Some guide in details here :
https://developer.android.com/reference/android/database/sqlite/SQLiteTransactionListener.html and
http://www.programcreek.com/java-api-examples/index.php?api=android.database.sqlite.SQLiteTransactionListener

Error with query in SugarORM

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 ?.

Calling a function in certain intervals

I'm making an android app which displays the list of male and female from database with a user specified age. I almost managed to write the code
the below is my code as far as I made
public class UserList{
private ArrayList<String> maleList;
private ArrayList<String> femaleList;} //getter setter for Arraylists
// method to get data
public UserList getUserLists (Context context, String age){
public UserList userList = new UserList();
public ArrayList<String> maleList = new ArrayList<String>();
public ArrayList<String> femaleList = new ArrayList<String>();
db = dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery(
"select * from USER_INFO where AGE = ?", new String[]{age});
if(cursor != null)
{
if(cursor.moveToFirst())
{
do{
String user_id = cursor.getString(cursor.getColumnIndex("USER_NAME"));
String gender = cursor.getString(cursor.getColumnIndex("GENDER"));
if(gender.equalsIgnorease("MALE"))
maleList.add(user_id);
else
femaleList.add(user_id);
}while(cursor.moveToNext());
cursor.close();
}
}
userList.setMaleList(maleList);
userList.setFemaleList(femaleList);
return userList;
}
But now I need to call this function for getting data from database to cursor in certain intervals like after every 5 minutes. Please help me in doing that the age variale used is age.
You should implement a broadcast receiver and setup an alarm scheduled at regular interval.
There is a simple tutorial on how to do that here : alarm-manager-example

How can insert a lot of items with ContentResolver fast

I'm trying to add words to user dictionary in bulks (tens of thousands of words).
I've tried to
Scanner scanner = new Scanner(file);
int counter = 0;
while(scanner.hasNextLine()) {
String word = scanner.nextLine();
UserDictionary.Words.addWord(getBaseContext(), word, 255, null, Locale.getDefault());
setProgress((float) counter++ * 100 / linesCount);
}
and I've also tried bulkinsert
ArrayList<String> words = new ArrayList<String>(capacity);
int counter = 0;
while(scanner.hasNextLine()) {
words.add(scanner.nextLine());
if (words.size() >= capacity) {
MyUserDictionary.addWords(getBaseContext(), words, Locale.getDefault());
words.clear();
setProgress((float) counter * 100 / linesCount);
}
counter++;
}
if (!words.isEmpty()) {
MyUserDictionary.addWords(getBaseContext(), words, Locale.getDefault());
}
And I've tried applyBatch.
All this method results with very long running time.
I know that sqlite can do better with transactions.
Do you know more faster way to do it?
EDIT1:
final ContentResolver resolver = context.getContentResolver();
final int COLUMN_COUNT = 5;
List<ContentValues> valueses = new ArrayList<ContentValues>(words.size());
for (String word: words) {
ContentValues values = new ContentValues(COLUMN_COUNT);
values.put(UserDictionary.Words.WORD, word);
values.put(UserDictionary.Words.FREQUENCY, DEFAULT_FREQUENCY);
values.put(UserDictionary.Words.LOCALE, null == locale ? null : locale.toString());
values.put(UserDictionary.Words.APP_ID, 0); // TODO: Get App UID
values.put(UserDictionary.Words.SHORTCUT, "");
valueses.add(values);
}
resolver.bulkInsert(UserDictionary.Words.CONTENT_URI, valueses.toArray(new ContentValues[valueses.size()]));

Insert Array in SQLite Database in android

I want to save weekdays in database, so i thought to store it by assigning int value to each day. i.e
1 -> Selected, 0 -> Not Selected.
Monday = 0/1
Tuesday = 0/1
.
.
.
.
.
Sunday = 0/1.
But this will make 7 columns in DB. So I was thinking if anyone can help me with this if I should store it in a single array and retrieve the values for further use. I was reading some examples over internet but didn't get it in a easy way.
To insert 7 values in one column you can use comma separator like this
where Total_Score_P1 is an string array
//string array
String[] Total_Score = new String[] { p1e1,p1e2,p1e3,p1e4,p1e5,p1e6 };
// Convderting it into a single string
String result_ScoreP1 = ("" + Arrays.asList(Total_Score_P1)).
replaceAll("(^.|.$)", " ").replace(", ", " , " );
result_ScoreP1 will be
// output of this
result_ScoreP1 = "p1e1,p1e2,p1e3,p1e4,p1e5,p1e6";
insert it as a single string in database and
when retrieve it in again break in parts like
// a string array list
// query fired
public ArrayList<String> rulTable(String id) {
// TODO Auto-generated method stub
ArrayList<String> Ruleob = new ArrayList<String>();
Cursor c_rule;
try
{
c_rule = db.query(NameTable, new String[]{
columns1
},
Rule_COurseID + "=" + id ,
null, null,
null, null, null);
c_rule.moveToFirst();
// if there is data available after the cursor's pointer, add
// it to the ArrayList that will be returned by the method.
if (!c_rule.isAfterLast())
{
do
{
Ruleob.add(c_rule.getString(0));
}
while (c_rule.moveToNext());
}
// let java know that you are through with the cursor.
c_rule.close();
}
catch(Exception e)
{
}
return Ruleob;
}
//list to get elements
ArrayList<String> ListOne = new ArrayList<String>();
ArrayList<String> row ;
try{
// received values
row = db.TheTable(id);
String r1 = row .get(0);
}
catch(Exception e)
{
}
StringTokenizer st2 = new StringTokenizer(r1, "||");
while(st2.hasMoreTokens()) {
String Desc = st2.nextToken();
System.out.println(Desc+ "\t" );
ListOne.add(Desc);
//
}
You can use a binary integer 1= selected 0 =Not Selected (1111111) (0000000)
total seven days so index 0=mon, 1=tues, 2=wed, 3=thurs, 4=friday, 5=sat, 6=sunday..and so on..
here 1111111 means all day selected, 0000000 all day not selected, 0001000 only thursday is selected.
I have also discovered a way i.e. convert your so called values to a JSON Array and then store the complete JSON String to an entity/field in Database.
It helps in serving the values easily and effectivly.
Create another table with a column for each day, boolean value. Make an association to this table by integer id (use a foreign key) This is the relational way of solving the problem.

Categories

Resources