Select data that is ordered from sqlite - android

I am trying to to get data with it ordered by a column but it is not working. Any idea on why?
public ArrayList<HashMap<String, String>> getMonthData(String month,String year, String name){
ArrayList<HashMap<String,String>> activityArrayList = new ArrayList<HashMap<String,String>>();
String selectQuery = "SELECT * FROM activity WHERE year='"+year+"' AND month='"+month+"' AND name=? ORDER BY day ASC";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery,new String[] { name });
if(cursor.moveToFirst()){
do{
HashMap<String, String> activityMap = new HashMap<String,String>();
activityMap.put("day",cursor.getString(2).toString());
activityArrayList.add(activityMap);
}while(cursor.moveToNext());
}
return activityArrayList;
}

The solution is that I stored day as TEXT so it was order lexicographical. So I have to cast it to REAL. Using "CAST(day AS REAL)".

Related

I want to retrieve data from SQL lite as an array of object using android

public List<Report> selectAll() {
List<Report> list = new ArrayList<Report>();
Report report = new Report();
int id,Temp;
String Date,Tank,Tankuse;
SQLiteDatabase db = this.getWritableDatabase();
String query = "select ID, Date,Temp,Tank,Tankuse from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query , null);
if (cursor.moveToFirst()) {
id=cursor.getInt(0);
report.setID(id);
Date=cursor.getString(1);
report.setDateTime(Date);
Temp=cursor.getInt(2);
report.setTemp(Temp);
Tank=cursor.getString(3);
report.setTank(Tank);
Tankuse=cursor.getString(4);
report.setTank(Tankuse);
list.add(report);
while (cursor.moveToNext());
}
return list;
}
how i can retrieve the data as array of objects this is my first time Using SQL lite i use 3 tires architecture in asp.net but i don't know how that's work here so can some tell me how or what i should change in my code to make it return an array of object ?
Example:
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}

How to correctly write big CRUD sqlite android app

I'm writing an app that manipulates with database consists of 3 tables. I created this database from json file using models (Worker model, specialty model) with getters and setters. Now I want to get specific info from this database. I'v already made it but my code is pretty silly. What I need is to change the architecture of my app but I don't know how exactly it should looks like.
This is the examples of my methods, and they are pretty week
This is how I add info into database. I like it, I think it's correct:
public void addWorker(Worker worker){
List<Specialty> specialty;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//fixind names
String f_name = fixName(worker.getF_name());
String l_name = fixName(worker.getL_name());
String birthday = fixDate(worker.getBirthday());
values.put(KEY_F_NAME, f_name);
values.put(KEY_L_NAME, l_name);
values.put(KEY_BIRTHDAY, birthday);
values.put(KEY_AVATR_URL, worker.getAvart_url());
specialty = worker.getSpecialty();
long worker_id = db.insert(TABLE_WORKERS,null,values);
//add unique specialty
for (Specialty spec: specialty){
createRelations(worker_id, spec.getSpecialty_id());
if (getCount(spec.getSpecialty_id()) == 0){
addSpecialty(spec);
}
}
}
And this is how I take info from database:
public String[] getFullInfo(String worker_name){
String selectQuery = "HUGE QUERY HERE "where workers.f_name =?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {worker_name});
String[] details = new String[5];
c.moveToFirst();
while (c.isAfterLast() == false){
details[0] = c.getString(c.getColumnIndex(KEY_F_NAME));
details[1] = c.getString(c.getColumnIndex(KEY_L_NAME));
details[2] = c.getString(c.getColumnIndex(KEY_BIRTHDAY));
details[3] = c.getString(c.getColumnIndex("age"));
details[4] = c.getString(c.getColumnIndex(KEY_SPEC_NAME));
c.moveToNext();
}
return details;
}
This is my another query and it has different return type:
public List<Map<String ,String>> getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
//making list of workers
List<Map<String ,String>> data = new ArrayList<Map<String,String>>();
c.moveToFirst();
while (c.isAfterLast() == false){
Map<String,String> datum = new HashMap<String,String>(2);
datum.put(KEY_F_NAME, c.getString(c.getColumnIndex(KEY_F_NAME)));
datum.put(KEY_L_NAME, c.getString(c.getColumnIndex(KEY_L_NAME)));
datum.put(KEY_BIRTHDAY, c.getString(c.getColumnIndex(KEY_BIRTHDAY)));
data.add(datum);
c.moveToNext();
}
return data;
}
and the third one, which also have different return type:
public List<String> getAllSpecs_Names(){
List<String> spec_names = new ArrayList<String>();
String selectQuery = "select * from " + TABLE_SPECIALTY;
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()){
do{
spec_names.add(c.getString(c.getColumnIndex(KEY_SPEC_NAME)));
}while (c.moveToNext());
}
return spec_names;
}
I know, that this is all wrong.
Please tell me how I should make all my queries.
It will be good if you give me the link to check how the app should look like
instead of returning a List or Map, you should better return a own CursorWrapper
so you could could look like this:
public WorkerCursor getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
return new WorkerCursor(cursor);
}
public static class WorkerCursor extends CursorWrapper {
/**
* Creates a cursor wrapper.
*
* #param cursor The underlying cursor to wrap.
*/
public WorkerCursor(Cursor cursor) {
super(cursor);
}
public Worker getWorker() {
return getWorkerAtCursor();
}
public Worker getWorker(int position) {
if (moveToPosition(position)) {
return getWorkerCursor();
} else {
return null;
}
}
private Worker getWorkerAtCursor() {
if (isBeforeFirst() || isAfterLast()) {
return null;
}
worker worker = new Worker();
worker.name = c.getString(c.getColumnIndex(KEY_F_NAME));
....
return worker;
}
}
and the same for your List, just with a other CursorWrapper
and don't forget to close the CursorWrapper, when it's no more needed, like in onDestroy of Activity and so

Key value pairs from sqlite to spinner

Could someone show me the correct way to achieve this.
I have setup a hashmap from a sqlite query as follows
public HashMap<String, String> getData(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_DEVICES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("device_name", cursor.getString(1));
user.put("id", cursor.getString(3));
}
cursor.close();
db.close();
// return user
return user;
}
I then want a spinner where the device names are displayed but when selected its the id that is then used for the next action
I was thinking something like this , but I am not sure exactly how.
private void loadLockScreenSpinner() {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> hm = db.getData();
String device_name = hm.get("device_name");
String id = hm.get("id");
ArrayAdapter<HashMap<String, String>> adapter = new ArrayAdapter<HashMap<String,String>>(this, android.R.layout.simple_spinner_item);
adapter.add(hm);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
devicesSpinner.setAdapter(adapter);
devicesSpinner.setWillNotDraw(false);
}
Not sure what to put in the onItemSelected

Android - SQLite delete and update data not working well

I created database with few tables, got 1 table called friend. A friend has few expenses, some expenses might share with another friend. Now i am trying to delete a friend, what i am trying to do is when the friend share expenses with another friend, the expense of the friend that shared with another friend will then added to another friend and the expense will not deleted. Then, the expenses that are not shared with another friend is directly deleted and will not added to any friend since the friend has many expenses. Now the problem is when i trying to add the expense to another friend, its not working. And i am not getting any error.
Here is my code : i think the problem occur inside if(sharerList.size()>1)...., since the rest of the code works well.
public void deleteFriend(String id) {
Log.d(LOGCAT, "delete");
SQLiteDatabase database = this.getWritableDatabase();
ArrayList<HashMap<String, String>> wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM FriendsExpenses WHERE friendId='" + id + "'";
SQLiteDatabase databaseread = this.getReadableDatabase();
Cursor cursor = databaseread.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("expenseId", cursor.getString(0));
wordList.add(map);
} while (cursor.moveToNext());
}
for (int a=0; a<wordList.size();a++){
HashMap<String, String> ValexpenseId = wordList.get(a);
for (Entry<String, String> entry : ValexpenseId.entrySet()) {
String value = entry.getValue();
String selectQuery2 = "SELECT * FROM FriendsExpenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread2 = this.getReadableDatabase();
Cursor cursor2 = databaseread2.rawQuery(selectQuery2, null);
ArrayList<HashMap<String, String>> sharerList = new ArrayList<HashMap<String, String>>();
if (cursor2.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("friendId", cursor2.getString(0));
wordList.add(map);
} while (cursor2.moveToNext());
}
else{};
if (sharerList.size() > 1){
String selectQuery3 = "SELECT expenseTotal FROM expenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread3 = this.getReadableDatabase();
Cursor cursor3 = databaseread3.rawQuery(selectQuery3, null);
String expenseTotal = null;
if (cursor3.moveToFirst()) {
do {
expenseTotal = cursor3.getString(cursor3.getColumnIndex("expenseTotal"));
} while (cursor3.moveToNext());
}
for (int b=0; b<sharerList.size();b++){
HashMap<String, String> ValfriendId = sharerList.get(b);
for (Entry<String, String> entry2 : ValfriendId.entrySet()) {
String value2 = entry2.getValue();
String currentSpend = currentSpending(value2);
double currentSpending = (Double.parseDouble(currentSpend));
double expTotal = (Double.parseDouble(expenseTotal));
double newSpending = currentSpending + ((expTotal/sharerList.size()) /sharerList.size()-1);
updateSpending(value2, newSpending);
}
}
}
else
{
String deleteQuery = "DELETE FROM expenses where expenseId='" + value + "'";
Log.d("query", deleteQuery);
database.execSQL(deleteQuery);
}
}
}
String deleteQuery = "DELETE FROM friends where friendId='" + id + "'";
String deleteQuery2 = "DELETE FROM FriendsExpenses where friendId='" + id + "'";
Log.d("query", deleteQuery2);
Log.d("query", deleteQuery);
database.execSQL(deleteQuery2);
database.execSQL(deleteQuery);
}
sharerList is empty because you never add any entries.
There are likely to be other copy/paste errors, such as getString(0) with SELECT *.

Getting the value of the ArrayList<HashMap<String,String>> for display

Hi I just want to know better on how to use this. Since I'm using this kind of method in doing my custom listView now I wanted to apply it since I love the approach on this but I don't know how I should do it. Anyway What I have is a database query where I get all the result from a search query in SQLite Database. Now I'm sure about the content of my query since I already tested it but when I display it the result always return the same output which is the last row of the query. For better understanding here's my code:
public ArrayList<HashMap<String,String>> getList(String search_param){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> hashmap = new HashMap<String,String>();
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
if (cursor.moveToFirst()) {
do {
item_list.put("column1", cursor.getString(0));
item_list.put("column2",cursor.getString(1));
list.add(hashmap);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
now to retrieve the list here's what I tried so far:
ArrayList<HashMap<String,String>> new_list;
DatabaseClass db = new DatabaseClass(getActivity());
new_list = db.getList("");
for(int i=0;i<new_list.size();i++){
HashMap<String,String> content = new HashMap<String, String>();
content = new_list.get(i);
Log.v("The hashmap",content.get("column1").toString());
Log.v("The hashmap",content.get("column2").toString());
}
now the content of my Database should be 1,2,3 for column1 and test1,test2,test3 for column2. but what I get from the result are 3,3,3 and test3,test3,test3
I also tried the method of doing
newlist.get(i).get("column1").toString; but it doesn't even solve the problem.
Any idea on what I should do about this?
Within do while you need to create instance for hashmap,
public ArrayList<HashMap<String,String>> getList(String search_param){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> hashmap;
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
if (cursor.moveToFirst()) {
do {
hashMap = new HashMap<String,String>();
hashMap.put("column1", cursor.getString(0));
hashMap.put("column2",cursor.getString(1));
list.add(hashmap);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
This works like charm with me
public ArrayList<HashMap<String, String>> getList(String search_param){
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
int colCount = cursor.getColumnCount();
int rowCount = cursor.getCount();
if (cursor.moveToFirst()) {
do {
HashMap<String, String> col = new HashMap<String, String>();
int size =cursor.getColumnCount();
for (int i = 0; i < size; i++) {
col.put(cursor.getColumnName(i), cursor.getString(i));
}
list.add(col);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}

Categories

Resources