I'm a noob to android and i am using a method to display a SQLite query. I want the row entry to display as row#, entryname, qty, amount (1. ferrari 2 $250,000), but instead it displays as (1. ferrari 2 null$250,000). I'm at my wits end because i can't figure out why i'm getting this pesky null. Nothing obvious jumps out at me in either my create entry or get data methods. Any help is greatly appreciated. Here is my code.
My create entry method:
public long createEntry(String coin, String quantity, String value) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, coin);
cv.put(KEY_QUANTITY, quantity);
cv.put(KEY_VALUE, value);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
My getdata method (for displaying in view):
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_VALUE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iQuantity = c.getColumnIndex(KEY_QUANTITY);
int iValue = c.getColumnIndex(KEY_VALUE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iQuantity) + " " + c.getString(iValue) + "\n";
}
return result;
}
Nothing obvious jumps out at me in either my create entry or get data methods.
Well from your question, if what you are expecting is 4 results separated by spaces then in the following...
ferrari 2 null$250,000
...you clearly have exactly that. If your create / get methods are OK then I'd start by suspecting your data source for the 'value'.
The 'null' is pre-pended to the value, in other words, it appears after the third space. Take a close look at the encoding of your data source and make sure you are handling it correctly.
Related
I made an quiz android app where the user get score every time he finish the quiz and after that the score will be saved in the database and after that the user can display the saved score. and my question is how I can display or sort these score on the page score from the biggest score to the smallest.
this is my code where I get the score and name of the user and set it on a textview:
TextView tv1 = (TextView) findViewById(R.id.TextView1);
DbHelper info = new DbHelper(this);
userInfo.open();
String data = userInfo.getData();
userInfo.close();
tv1.setText(data);
my getData method:
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_SCORE};
Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, null);
String result ="";
int TheRow = c.getColumnIndex(KEY_ID);
int TheName = c.getColumnIndex(KEY_NAME);
int TheScore = c.getColumnIndex(KEY_SCORE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(TheRow ) + " " + c.getString(TheName ) + " " + c.getString(TheScore ) + "\n";
}
return result;
}
You can set ascending or descending in the last argument of your query. In your case, your getData() method can return your string with the KEY_SCORE column in descending order by changing the query line to this:
Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, KEY_SCORE + " DESC");
Good Luck!
I've got two tables
Workout Table
Workout_ID --------- Workout Name
1 --------------------------- Chest
2 ---------------------------- Back
Date of Workouts Table
Date_ID------- Date of Workout------ Workout_ID
1-----------------------22/12/13---------------- 1
2---------------------- 23/12/13---------------- 2
Within android, using MySqlite currently:
i have these exact tables.
However when i come to OUTPUT my 'Date of Workouts Table' onto the screen, what MySQLite Code will i need to do so? General points would be really appreciated.
Somehow i need to take the 'Workout_ID' and compare it to the 'Workout_ID' in the Workout Table and generate 'Chest' and then output that
EDIT Here i've got my code which Outputs whe Workout_ID which is present in the Date of Workouts Table
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);
}
System.out.println(workoutName2);
return workoutName2;
}
HERE I'm trying to query my WorkoutTable WHERE my workout_id is equal to the workoutSlectedNameInfo
So i'm trying to go down the list of Workout_ID in my 'Date of Workouts Table' and compare the 1 and 2 to the Workout Table - This doesn't work - Will this Join statement allow me to do this?
public String test(String workoutSelectedNameInfo) {
// TODO Auto-generated method stub
String Weight = "";
open();
ourDatabase = ourhelper.getReadableDatabase();
Cursor c = ourDatabase
.rawQuery(
"SELECT workout_name FROM WorkoutTable WHERE workout_id = ?",
new String[] { workoutSelectedNameInfo });
int iWeight = c.getColumnIndex(KEY_WORKOUT_NAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
Weight = Weight + c.getString(iWeight) + "\n";
}
c.close();
ourDatabase.close();
return Weight;
// TODO Auto-generated method stub
}
here db proper innitialised instance
String sql = "select workoutname from WorkoutTable as wt,WorkoutDayTable wdt where wt.Workout_ID = wdt.Workout_ID ";
Cursor cursor = db.rawQuery(sql,null);
The query
SELECT * FROM Workout LEFT JOIN DateofWorkout ON (Workout.Workkout_ID = DateofWorkout.Workout_ID) WHERE Workout.Workout_ID = "??????" -- use your ID to find the data
------------------------------------------------------------------
There are three basic JOINS
The CROSS JOIN
The INNER JOIN
The OUTER JOIN
Plus read this simple guide you really need, anyhow just read the GUIDE, after reading you won't ask question regarding queries anymore
Tutorial About SQLite and Android
Edited
dbHelper = new DbHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.db.rawQuery("SELECT * FROM Workout LEFT JOIN DateofWorkout ON Workout.Workkout_ID = DateofWorkout.Workout_ID", null);
while(c.moveToNext())
{
// your code goes here
}
I have database which contains "date" column and "item" column.
I want that user could update specific row in the database.
I trying to do it with update method in SQLiteDatabase class.
My problem is that i dont know how to make update method find exactly the row i want.
I saw some example that use it with parameters from one word.
like this:
ourDatabase.update(tableName, cvUpdate, rowId + "=" + item , null);
My problem is that i want to update the row that have specific item and date. so the name of the item alone is not enough.
I tried this code below but its didnt work, hope youll can help me.
public void updateEntry(String item, String date) throws SQLException{
String[] columns = new String[]{myItem, myDate};
Cursor c = ourDatabase.query(tableName, columns, null, null, null, null, null);
long position;
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(date, myDate);
cvUpdate.put(item, myExercise);
int itemAll = c.getColumnIndex(myItem);
int dateAll = c.getColumnIndex(myDate);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if (c.getString(itemAll).equals(myItem) && c.getString(dateAll).equals(myDate))
{
position = c.getPosition();
break;
}
}
ourDatabase.update(tableName, cvUpdate, rowId + "=" + position , null);
}
First, the columns String[] is supposed to contain column names, such as "_ID", or whatever are the column names you have used. Given that you compare the content of the column myItem with the object myItem, I assume there is a confusion somewhere here.
Secondly, rowId and position are different things in SQL, especially if you delete rows, as the row id usually is autoincrement, and especially since your query is not explicitely sorted. Replacing c.getPosition() by c.getLong(c.getColumnIndex(ID_COLUMN)) would make more sense.
Thirdly, sql is nice because you can query it. For example, rather than get all items and loop to find the matching date and item, you can :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
Cursor c = ourDatabase.query(tableName, columns, whereClause, whereArgs, null, null, null);
instead of your for loop.
Forthly, you can even make the query in the update :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
ourDatabase.update(tableName, cvUpdate, whereClause, whereArgs);
Extra tip: use full caps variable names for contants such as column names, it help with readability.
this is my code used which i use for making method
String item = item1.getText().toString();
item = item.toLowerCase();
String date = getDate();
edited = new Datahelper(this);
edited.open();
String returnedprice = edited.getprice(item,date);
String returneddetail = edited.getdetail(item,date);
edited.close();
price.setText(returnedprice);
details.setText(returneddetail);
and this is my code of method that i am using for getting that string but here i dont know how to use the 2nd date string so that the string price that return is from a row that contains that item and that date.. please give me the code of how to do it..
public String getprice(String item ,String date) {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID,
KEY_CATEGORY,KEY_DATE,KEY_PRICE,KEY_DETAILS};
Cursor v =ourDatabase.query(DATABASE_TABLE, columns, KEY_CATEGORY + " ='" + item
+"'",null,null, null, null);
if(v!=null){
String price = v.getString(3);
return price;
}
return null;
}
public String getdetail(String item,String date) {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID,
KEY_CATEGORY,KEY_DATE,KEY_PRICE,KEY_DETAILS};
Cursor v =ourDatabase.query(DATABASE_TABLE, columns, KEY_CATEGORY + " ='" + item +
"'",null,null, null, null);
if(v!=null){
String detail = v.getString(4);
return detail;
}
return null;
}
So probably you want to use two arguments in select query so:
You can use two methods:
rawQuery()
query()
I will give you basic example for both cases.
First:
String query = "select * from Table where someColumn = ? and someDateColumn = ?";
Cursor c = db.rawQuery(query, new String[] {textValue, dateValue});
Explanation:
So i recommend to you use ? that is called placeholder.
Each placeholder in select statement will be replaced(in same order so first placeholder will be replaced by first value in array etc.) by values from selectionArgs - it's String array declared above.
Second:
rawQuery() method was easier to understand so i started with its. Query() method is more complex and has a little bit more arguments. So
columns: represents array of columns will be selected.
selection: is in other words where clause so if your selection is
KEY_COL + " = ?" it means "where " + KEY_COL + " = ?"
selectionArgs: each placeholder will be replaced with value from this
array.
groupBy: it's multi-row (grouping) function. more
about
having: this clause is always used with group by clause here is
explanation
orderBy: is clause used for sorting rows based on one or multiple
columns
Also method has more arguments but now you don't need to care about them. If you will, Google will be your friend.
So let's back to explanation and example:
String[] columns = {KEY_COL1, KEY_COL2};
String whereClause = KEY_CATEGORY " = ? and " + KEY_DATE + " = ?";
String[] whereArgs = {"data1", "data2"};
Cursor c = db.query("Table", columns, whereClause, whereArgs, null, null, null);
So whereClause contains two arguments with placeholder for each. So first placeholder will be replaced with "data1" and second with "data2".
When query is performed, query will look like:
SELECT col1, col2 FROM Table WHERE category = 'data1' AND date = 'data2'
Note: I recommend to you have look at Android SQLite Database and ContentProvider - Tutorial.
Also i recommend to you an usage of placeholders which provide safer and much more readable and clear solutions.
You should read any SQL tutorial to find out what a WHERE clause it and how to write it.
In Android, the selection parameter is the expression in the WHERE clause.
Your query could be written like this:
c = db.query(DATABASE_TABLE, columns,
KEY_CATEGORY + " = ? AND " + KEY_DATE + " = ?",
new String[] { item, date },
null, null, null);
I coudn't imagine why my score is not descending. It was the first digit only to sort. help me guys to analyze this code and tell me whats wrong also the answer.
public String getData() {
Cursor c= ourDatabase.query(DATABASE_TABLE, new String[] {KEY_NAME, KEY_SCORE},
null, null, null, null, KEY_SCORE +" DESC");
String result = "";
int iname = c.getColumnIndex(KEY_NAME);
int iscore = c.getColumnIndex(KEY_SCORE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iname) + " "+ c.getInt(iscore)+ "\n";
}
return result;
}
The problem is probably that KEY_SCORE is being stored as a string and not as a number.
There is more than one way to fix this. Cast the score to an integer or float:
cast(Key_Score as float) desc
Or, if it is an integer with no leading 0s, the following trick works:
len(Key_Score) desc, key_score desc
However, in some databases the len() function might be spelled length() or something else.