i am having problem inserting and updating values correctly into the database. I have a database, with two tables each with 3 columns DATE, NUM_X, NUM_Y. The two different tables contain the same columns, the only difference in the way values are inserted is that the HOURS_TABLE will take HH (the current hour of the day) and DATE_TABLE will take a short time string dd/MM/yyyy.
The values are not being inserted into new rows, but updating the values of the first row. Both tables currently have only one row.
public static final String HOURS_TABLE = "HOURS_TABLE";
public static final String DATE_TABLE = "DATE_TABLE";
public static final String CreateHoursTable = "create table "+
HOURS_TABLE +" ("+DATE+" string not null, "+NUM_X+
" integer default 0,"+NUM_Y+" integer default 0)";
public static final String CreateDateTable = "create table "+
DATE_TABLE +" ("+DATE+" string not null, "+NUM_X+"
integer default 0,"+NUM_Y+" integer default 0)";
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL(CreateDateTable);
db.execSQL(CreateHoursTable);
}
Two different kinds of date strings could be passed in, on formatted dd/MM/yyyy (short date string )and another for HH (hours)
public long createEntry(int x, int y, String date, int Version_Zero_HoursTable_One_DateTable)
{
/*
* first grab the values needed to increment the database values
* */
Cursor c ;
String[] column = new String[]{DATE,NUM_X,NUM_Y};
if(Version_Zero_HoursTable_One_DateTable == 0)
{
c = ourDatabase.query(HOURS_TABLE, column, date, null, null,
null, null);
}
else
{
c = ourDatabase.query(DATE_TABLE, column, date, null, null,
null, null);
}
int current_x =0;
int current_y = 0;
String current_day = "";
int iX = c.getColumnIndex(NUM_X);
int iY = c.getColumnIndex(NUM_Y);
int iDate = c.getColumnIndex(DATE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
current_x += c.getInt(iX);
current_y += c.getInt(iY);
current_day = c.getString(iDate);
}
ContentValues cv = new ContentValues();
cv.put(NUM_X, smokes+current_smokes);
cv.put(NUM_Y, cravings+current_cravings);
cv.put(DATE, date);
the WHEREargs string is my variable for a where clause, so when the selected DATE from the database equals date it will update that selected column, and if nothing is selected (current_day.equals("")), the statement to insert a new row will execute.
String WHEREargs = DATE+"="+date;
if(Version_Zero_HoursTable_One_DateTable == 0)
{
if(current_day.equals(""))
{
return ourDatabase.insert(HOURS_TABLE, null, cv);
}
else
{
return ourDatabase.update(HOURS_TABLE, cv, WHEREargs, null);
}
}
else
{
if(current_day.equals(""))
{
return ourDatabase.insert(DATE_TABLE, null, cv);
}
else
{
return ourDatabase.update(DATE_TABLE, cv, WHEREargs, null);
}
}
}
any help would be greatly appreciated , Thankyou .
You are using the date variable wrong.
A date value such as 24/03/2014 cannot be directly used as a WHERE expression; it would be interpreted as two integer divisions.
Similarly, a string such as DATE = 24/03/2014 cannot be used as a WHERE expression either, because it compares the value in the date column to a number.
In SQL, strings must be enclosed in 'single quotes'.
However, to avoid formatting problems and SQL injection attacks, it is a better idea to use parameters:
String where = DATE + "= ?";
String[] whereArgs = new String[] { date };
...
db.query(..., where, whereArgs, ...);
Related
I am wondering if its possible to query existing database and detect if same value is in the database when inserting.
This is method of inserting in a class extends SQLiteOpenHelper
public void insertTimeTable_Schedule(String title, String subtitle, String color_text, String color_text_bg,
String mon, String tue, String wed, String thus, String fri, String sat, String sun,
String start_time, String end_time){
sqLiteDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE,title);
values.put(COLUMN_SUBTITLE,subtitle);
values.put(COLUMN_COLOR_TEXT,color_text);
values.put(COLUMN_COLOR_TEXT_BG,color_text_bg);
values.put(COLUMN_MON,mon);
values.put(COLUMN_TUE,tue);
values.put(COLUMN_WED,wed);
values.put(COLUMN_THUS,thus);
values.put(COLUMN_FRI,fri);
values.put(COLUMN_SAT,sat);
values.put(COLUMN_SUN,sun);
values.put(COLUMN_START_TIME,start_time);
values.put(COLUMN_END_TIME,end_time);
sqLiteDatabase.insert(TABLE_TIMETABLE, null, values);
}
Now I'd like to detect and make error message if there is same start_time in COLUMN_START_TIME when inserting new table data.
I tried to display values from database using method will be indicated below, and this will show everything I inserted
public String getData_database(){
sqLiteDatabase = this.getReadableDatabase();
String[] columns = new String[]{KEY_ID, COLUMN_TITLE,COLUMN_SUBTITLE,COLUMN_COLOR_TEXT,COLUMN_COLOR_TEXT_BG,
COLUMN_MON,COLUMN_TUE, COLUMN_WED,COLUMN_THUS, COLUMN_FRI,COLUMN_SAT,COLUMN_SUN,
COLUMN_START_TIME,COLUMN_END_TIME};
#SuppressLint("Recycle")
Cursor cursor =
sqLiteDatabase.query(TABLE_TIMETABLE,columns,null,null,null,null,null);
int iId = cursor.getColumnIndex(KEY_ID);
int iTitle = cursor.getColumnIndex(COLUMN_TITLE);
int iTextcolor = cursor.getColumnIndex(COLUMN_COLOR_TEXT);
int iTextBgcolor = cursor.getColumnIndex(COLUMN_COLOR_TEXT_BG);
int iSubtitle = cursor.getColumnIndex(COLUMN_SUBTITLE);
int iStarttime = cursor.getColumnIndex(COLUMN_START_TIME);
int iEndtime = cursor.getColumnIndex(COLUMN_END_TIME);
StringBuilder result = new StringBuilder();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.append("Id: ").append(cursor.getString(iId)).append("\n").append("Title: ").append(cursor.getString(iTitle)).append("\n").append("SubTitle: ").append(cursor.getString(iSubtitle)).append("\n").append("Text Color: ").append(cursor.getString(iTextcolor)).append("\n").append("Text BG Color: ").append(cursor.getString(iTextBgcolor)).append("\n").append("Start Time: ").append(cursor.getString(iStarttime)).append("\n").append("End Time: ").append(cursor.getString(iEndtime)).append("\n\n");
}
sqLiteDatabase.close();
return result.toString();
}
If you have any advice, I'd love to hear.
You can have a method that returns a boolean after querying the table. Then in your insert statement you check if the response is true, then show whatever error, otherwise, insert the record.
This method:
public boolean existsStartTime(String start_time){
sqLiteDatabase = this.getWritableDatabase();
String sql = "SELECT 1 FROM " + TABLE_TIMETABLE + " WHERE " + COLUMN_START_TIME + " = ?";
Cursor c = sqLiteDatabase.rawQuery(sql, new String[] {start_time});
boolean result = c.moveToFirst();
c.close();
sqLiteDatabase.close();
return result;
}
will return true if the value of the variable start_time exists in the table or false if it does not exist.
You can check it like:
String start_time = "<value here>";
if (existsStartTime(start_time)) {
<error message here>
} else {
insertTimeTable_Schedule(...);
}
I want to create a android sqlite table with only one single row, for insert or update and read, how can i do that, cause i only know how to create mulitiple row
the table contain only 1 single row , is for user insert data and store , when read the data will come out , and last the update mean it will override the data which in that row.
this is my DBHelperNote.java
public static final String TABLE_GOAL = "goal";
public static final String GOAL_ID= "goal_id";
public static final String GENDER = "gender";
public static final String AGE = "age";
public static final String HEIGHT = "height";
public static final String WEIGHT = "weight";
public static final String GOAL = "goal";
private static final String CREATE_TABLE_GOAL = "CREATE TABLE " + TABLE_GOAL + " (" +
GOAL_ID + " INTEGER PRIMARY KEY, " +
GENDER + " text not null, " +
AGE + " text not null, "+
HEIGHT + " text not null, "+
WEIGHT + " text not null, "+
GOAL + " text not null "+
" );";
this is SQLControlerWeight.java
public void insertGoal(String gd,String age,String hg,String wg,,String gl) {
ContentValues cv = new ContentValues();
cv.put(DBHelperNote.GENDER, gd);
cv.put(DBHelperNote.AGE, age);
cv.put(DBHelperNote.HEIGHT, hg);
cv.put(DBHelperNote.WEIGHT, wg);
cv.put(DBHelperNote.GOAL, gl);
database.insert(DBHelperNote.TABLE_GOAL, null, cv);
}
public Cursor readGoal() {
String[] allColummn = new String[] {
DBHelperNote.GOAL_ID,
DBHelperNote.GENDER,
DBHelperNote.AGE,
DBHelperNote.HEIGHT,
DBHelperNote.WEIGHT,
DBHelperNote.GOAL,
};
Cursor c = database.query(DBHelperNote.TABLE_GOAL, allColummn, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
this actually is the method to read data put but it is from array mean multiple row , but i don't Know how to change it to only call one row
dbconnection = new SQLControlerWeight(this);
dbconnection.openDatabase();
Cursor cursor = dbconnection.readGoal();
String[] from = new String[]{
DBHelperNote.GOAL_ID,
DBHelperNote.GENDER,
DBHelperNote.AGE,
DBHelperNote.HEIGHT,
DBHelperNote.WEIGHT,
DBHelperNote.GOAL,
};
int[] to = new int[]{
R.id.goal_id,
R.id.field_gender,
R.id.field_age,
R.id.field_height,
R.id.field_weight,
R.id.field_goal,
};
As you will be having GOAL_ID ones inserted you can modify you insert function as
public void insertGoal(String goal_id, String gd,String age,String hg,String wg,,String gl) {
ContentValues cv = new ContentValues();
if (goal_id != null){
cv.put(DBHelperNote.GOAL_ID, goal_id);
}
cv.put(DBHelperNote.GENDER, gd);
cv.put(DBHelperNote.AGE, age);
cv.put(DBHelperNote.HEIGHT, hg);
cv.put(DBHelperNote.WEIGHT, wg);
cv.put(DBHelperNote.GOAL, gl);
database.replace(DBHelperNote.TABLE_GOAL, null, cv);
}
Modification done is changed insert to replace, which will make sure if primary key value is provided and row exists with that id then it will replace the existing row without creating new one. Most important is the if condition for checking whether goal_id is null or not, if null then don't provide that in contentvalue.
Modify the if condition properly for proper comparison for Goal_id as i have just used the one i can visualize from your question content.
Use RawQuery method its little bit easier.
c1 = db.rawQuery("select * from Table_Name", null);
c1.moveToFirst();
do {
str = c1.getString(c1.getColumnIndex("FieldName"));
ab.add(str);
} while (c1.moveToNext());
Android, implementing SQLite
These are the tables i have:
http://postimg.org/image/jafsx39h7/
I have the code:
public String getWorkoutNameInfo() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_DATE_OF_WORKOUT,
KEY_WORKOUT_NAME, KEY_DATE };
Cursor c = ourDatabase.query(TABLE_DATE_WORKOUT, columns, null, null,
null, null, null, null);
String workoutName2 = "";
int iWorkoutID = c.getColumnIndex(KEY_WORKOUT_NAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
workoutName2 = workoutName2 + c.getString(iWorkoutID);
}
return workoutName2;
}
This returns workoutName2 which is '2 1 2'
Now i need to look up the value for 2 in my WorkoutTable and return 'Back' and produce 'Back,Chest,Back' so i can out put that onto my screen instead of 2 1 2.
I understand I'll be using a JOIN statement? However i'm having no luck implementing it.
My Table Coding:
// WORKOUT TABLE - COLUMN NAMES
public static final String KEY_WORKOUT = "workout_id";
public static final String STRING_WORKOUT = "workout_name";
// DATE OF WORKOUT TABLE - COLUMN NAMES
public static final String KEY_DATE_OF_WORKOUT = "date_of_workout_id";
public static final String KEY_DATE = "date_of_workout";
public static final String KEY_WORKOUT_NAME = "workout_id";
//TABLE NAMES
private static final String TABLE_WORKOUT = "WorkoutTable";
private static final String TABLE_DATE_WORKOUT = "DateofWorkout";
Here is my attempt:
public String test(String workoutSelectedNameInfo) {
// TODO Auto-generated method stub
String NAMEofWorkout = "";
open();
ourDatabase = ourhelper.getReadableDatabase();
Cursor c = ourDatabase
.rawQuery(
"SELECT * FROM WorkoutTable LEFT JOIN DateofWorkout ON (WorkoutTable.workout_id = DateofWorkout.workout_id) WHERE workout_id = ?",
new String[] { "2" });
int iDateofWorkoutsWorkoutId = c.getColumnIndex(KEY_WORKOUT_NAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
NAMEofWorkout = NAMEofWorkout + c.getString(iDateofWorkoutsWorkoutId);
}
c.close();
ourDatabase.close();
System.out.println(NAMEofWorkout);
return NAMEofWorkout;
}
HOWEVER When it output the 'NameofWorkout' which SHOULD be Chest,Back,Chest i receive nothing at all, absolutely blank.
When I enter your data into a SQLite instance on my machine and then execute your query, I get the following error:
Error: ambiguous column name: workout_id
In the query, changing WHERE workout_id to WHERE DateofWorkout.workout_id makes the error go away.
This problem happens because there are two columns named workout_id in the result, and you must disambiguate your subsequent references. Because of this, you probably must also change
c.getColumnIndex(KEY_WORKOUT_NAME)
to
c.getColumnIndex(TABLE_DATE_WORKOUT + "." + KEY_WORKOUT_NAME)
when you make use of the results later.
I created two table weekone and weektwo in my database. They a both uploaded the data in the database succussfully taken from EditTexts, however when I want to view the database by pressing Viewbutton, the application crashes.
This is how i am saving entries from Editext in database in table weekone
String treadmillTimings = durOnTreadmill.getText().toString();
DatabaseManager entry = new DatabaseManager(this);
entry.open();
entry.createEntry(treadmillTimings);
entry.close();
String stepperTimings = durOnStepper.getText().toString();
DatabaseManager entry1 = new DatabaseManager(this);
entry1.open();
entry1.week1createEntry1(stepperTimings);
entry1.close();
String stationaryRowingTimings = durOnStationaryRowing.getText().toString();
DatabaseManager entry2 = new DatabaseManager(this);
entry2.open();
entry2.week1createEntry2(stationaryRowingTimings);
entry2.close();
String exerciseBikeTimings = durOnExerciseBike.getText().toString();
DatabaseManager entry3 = new DatabaseManager(this);
entry3.open();
entry3.week1createEntry3(exerciseBikeTimings);
entry3.close();
String ellipticalTrainerTimings = durOnEllipticalTrainer.getText().toString();
DatabaseManager entry4 = new DatabaseManager(this);
entry4.open();
entry4.week1createEntry4(ellipticalTrainerTimings);
entry4.close();
Writing Entries in table weekone
//creating entry in table for treadmill in table week 1 with the help of ContentValues
public long createEntry(String treadmillTimings)
{
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
//enterting each exercise name corresponding to their respective edit Texts
cv.put(KEY_EXERCISENAME, "Treadmill");
cv.put(KEY_DURATION, treadmillTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv);
}
//creating entry in table for stepperTimings in table week 1 with the help of ContentValues
public long week1createEntry1 (String stepperTimings)
{
ContentValues cv1 = new ContentValues();
cv1.put(KEY_EXERCISENAME, "Stepper");
cv1.put(KEY_DURATION, stepperTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv1);
}
//creating entry in table for Stationary Rowing in table week 1 with the help of ContentValues
public long week1createEntry2 (String stationaryRowingTimings)
{
ContentValues cv2 = new ContentValues();
cv2.put(KEY_EXERCISENAME, "Stationary Rowing");
cv2.put(KEY_DURATION, stationaryRowingTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv2);
}
//creating entry in table for exercise bike in table week 1 with the help of ContentValues
public long week1createEntry3 (String exerciseBikeTimings)
{
ContentValues cv3 = new ContentValues();
cv3.put(KEY_EXERCISENAME, "Exercise Bike");
cv3.put(KEY_DURATION, exerciseBikeTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv3);
}
//creating entry in table for elliptical trainer in table week 1 with the help of ContentValues
public long week1createEntry4 (String ellipticalTrainerTimings)
{
ContentValues cv4 = new ContentValues();
cv4.put(KEY_EXERCISENAME, "Stationary Rowing");
cv4.put(KEY_DURATION, ellipticalTrainerTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv4);
}
Displaying entries in database
//displaying/reading data in the table using cursor
public String week1getData()
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_EXERCISENAME, KEY_DURATION};
Cursor cur = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
//creating a result(string type variable) to store the text and display it.
String result = "";
int iRow = cur.getColumnIndex(KEY_ROWID);
int iExerciseName = cur.getColumnIndex(KEY_EXERCISENAME);
int iDuration = cur.getColumnIndex(KEY_DURATION);
// cursor start from the first position, keeps moving to the next as long as the position in not after that last.
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext())
{
/*getting the rows, exercise name and duration in the tables of database and setting it to result.
.The next time it loops, it will still have the prevoius result*/
result = result + cur.getString(iRow) + " " + cur.getString(iExerciseName) + " " + cur.getString(iDuration) + "\n";
}
return result;
}
All the code is same for tableweektwo except for the below
public String week2getData() <------- ERROR IS IN THIS METHOD, BASED ON LOGCAT
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_EXERCISENAME, KEY_DURATION};
Cursor cur = ourDatabase.query(DATABASE_TABLE2, columns, null, null, null, null, null);
//creating a result(string type variable) to store the text and display it.
String result = "";
int iRow = cur.getColumnIndex(KEY_ROWID);
int iExerciseName = cur.getColumnIndex(KEY_EXERCISENAME);
int iDuration = cur.getColumnIndex(KEY_DURATION);
// cursor start from the first position, keeps moving to the next as long as the position in not after that last.
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext())
{
/*getting the rows, exercise name and duration in the tables of database and setting it to result.
.The next time it loops, it will still have the previous result*/
result = result + cur.getString(iRow) + " " + cur.getString(iExerciseName) + " " + cur.getString(iDuration) + "\n";
}
return result;
}
Addtionally I did exactly the same for weektwowhatever i did for weekone. please tell me where am I going wrong. thanks
Saw your logcat and it seems that your database is closed when you try to read the data. I would like to suggest to not to open and close the database so frequently. This creates a lot of confusion in the code. You can try to open the database at onCreate of your parent Activity(the context that you pass) and close it in onDestroy() only.
EDIT: You can refer this for design patterns.
EDIT 2 : You can confirm if this is the problem or not by opening the database only once and never closing it to see if the problem goes away. If it does the refer the linked article in previous edit.
What is the most efficient method of showing my data in descending order?
public String getRank() {
String[] rank = new String[]{ KEY_ROWID };
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, null); //reading information from db.
String rankResult = "";
int iRow = c.getColumnIndex(KEY_ROWID); //Cursor looking for column setting equal to these ints.
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//Move to first row - where cursor starts and moves to next row as long it is not after last row.
rankResult = rankResult + c.getString(iRow) + "\n";
//Returning value of row that it is currently on.
}
return rankResult; //returning result
}
public String getName() {
String[] name = new String[]{ KEY_NAME };
Cursor c = scoreDb.query(DATABASE_TABLE, name, null, null, null, null, null); //reading information from db.
String nameResult = "";
int iRow1 = c.getColumnIndex(KEY_NAME); //Cursor looking for column setting equal to these ints.
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//Move to first row - where cursor starts and moves to next row as long it is not after last row.
nameResult = nameResult + c.getString(iRow1) + "\n";
//Returning value of row that it is currently on.
}
return nameResult; //returning result
}
public String getScore() {
String[] score = new String[]{ KEY_SCORE };
Cursor c = scoreDb.query(DATABASE_TABLE, score, null, null, null,null, null); //reading information from db.
String scoreResult = "";
int iRow2 = c.getColumnIndex(KEY_SCORE); //Cursor looking for column setting equal to these ints.
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//Move to first row - where cursor starts and moves to next row as long it is not after last row.
scoreResult = scoreResult + c.getString(iRow2) + "\n";
//Returning value of row that it is currently on.
}
return scoreResult; //returning result
}
Query has two syntax, the syntax you are using, last column represents orderBy, you just need to specify on what column you want to do orderBy +"ASC" (or) orderBy +"DESC"
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
Refer this documentation to understand more about query() method.
return database.rawQuery("SELECT * FROM " + DbHandler.TABLE_ORDER_DETAIL +
" ORDER BY "+DbHandler.KEY_ORDER_CREATED_AT + " DESC"
, new String[] {});
Cursor c = scoreDb.query(Table_Name, score, null, null, null, null, Column+" DESC");
Try this
According to docs:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
and your ORDER BY param means:
How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the default
sort order, which may be unordered.
So, your query will be:
Cursor cursor = db.query(TABLE_NAME, null, null,
null, null, null, KEY_ITEM + " DESC", null);
public List getExpensesList(){
SQLiteDatabase db = this.getWritableDatabase();
List<String> expenses_list = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME ;
Cursor cursor = db.rawQuery(selectQuery, null);
try{
if (cursor.moveToLast()) {
do{
String info = cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION));
expenses_list.add(info);
}while (cursor.moveToPrevious());
}
}finally{
cursor.close();
}
return expenses_list;
}
This is my way of reading the record from database for list view in descending order. Move the cursor to last and move to previous record after each record is fetched. Hope this helps~
Cursor c = myDB.rawQuery("SELECT distinct p_name,p_price FROM products order by Id desc",new String[]{});
this works for me!!!
you can do it with this
Cursor cursor = database.query(
TABLE_NAME,
YOUR_COLUMNS, null, null, null, null, COLUMN_INTEREST+" DESC");
SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns.
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
rank,
null,
null,
null,
null,
COLUMN + " DESC",
null);
We have one more option to do order by
public Cursor getlistbyrank(String rank) {
try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
} catch (SQLException sqle) {
Log.e("Exception on query:-", "" + sqle.getMessage());
return null;
}
}
You can use this two method for order
This a terrible thing! It costs my a few hours!
this is my table rows :
private String USER_ID = "user_id";
private String REMEMBER_UN = "remember_un";
private String REMEMBER_PWD = "remember_pwd";
private String HEAD_URL = "head_url";
private String USER_NAME = "user_name";
private String USER_PPU = "user_ppu";
private String CURRENT_TIME = "current_time";
Cursor c = db.rawQuery("SELECT * FROM " + TABLE +" ORDER BY " + CURRENT_TIME + " DESC",null);
Every time when I update the table , I will update the CURRENT_TIME for sort.
But I found that it is not work.The result is not sorted what I want.
Finally, I found that, the column "current_time" is the default row of sqlite.
The solution is, rename the column "cur_time" instead of "current_time".
About efficient method. You can use CursorLoader. For example I included my action. And you must implement ContentProvider for your data base. https://developer.android.com/reference/android/content/ContentProvider.html
If you implement this, you will call you data base very efficient.
public class LoadEntitiesActionImp implements LoaderManager.LoaderCallbacks<Cursor> {
public interface OnLoadEntities {
void onSuccessLoadEntities(List<Entities> entitiesList);
}
private OnLoadEntities onLoadEntities;
private final Context context;
private final LoaderManager loaderManager;
public LoadEntitiesActionImp(Context context, LoaderManager loaderManager) {
this.context = context;
this.loaderManager = loaderManager;
}
public void setCallback(OnLoadEntities onLoadEntities) {
this.onLoadEntities = onLoadEntities;
}
public void loadEntities() {
loaderManager.initLoader(LOADER_ID, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(context, YOUR_URI, null, YOUR_SELECTION, YOUR_ARGUMENTS_FOR_SELECTION, YOUR_SORT_ORDER);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}