Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This function keeps on returning a blank string.
public String getRandomWord() {
int id = (int)(Math.random())*(numberOfRows())+1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select word from words where id="+id+"", null );
String s = "";
if (res.moveToFirst())
s = res.getString(res.getColumnIndex("word"));
res.close();
return s;
}
The reason for the returning of a blank string is that res.moveToFirst() is false (so your SQL query result was empty) and the if-block will never get run, and thus s will always keep its initial value of "".
The alternative reason could be that the expression is true, but res.getString(res.getColumnIndex("word")) returns a blank string.
If you want a random row (word) then try using :-
public String getRandomWord() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select word from words order by random() limit 1", null );
String s = "";
if (res.moveToFirst())
s = res.getString(res.getColumnIndex("word"));
res.close();
return s;
}
This does assume that there are rows in the table, if there aren't then you'd still get a blank result.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am currently trying to display a report for out of stock items. I have the function readOutData() implemented into my report activity and it displays all of the products but how can I edit my function to only show products whose quantity is 0? Here is the code for my current function that just reads all of the product data. I added a comment showing what I want it to do, I'm just not sure how to format it.
Cursor readOutData() {
String query = "SELECT * FROM " + TABLE_NAME; //WHERE quantity = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
This code should work, assuming that the columns are correct
String query = "SELECT * FROM " + TABLE_NAME + " WHERE quantity = 0";
Although use of a PreparedStatement would be better.
I need to get a string from my room database and set it as text in a textview i'm using this code in my dao
#Query("SELECT question, question_heat, question_gender FROM questions WHERE question_heat = :heat AND question_gender = :gender" +
" ORDER BY RANDOM() LIMIT 1")
String getQuestion(int heat, int gender);
i just want to get a random question from my question database.I get this error:
error: Not sure how to convert a Cursor to this method's return type String getQuestion(int heat, int gender);
in the build output says the error is in the query
i'm really new in room i was using sqlopenhelper for a while and i don't really know what to do here.
i found some codes in google but they were for lists of data and i want to get just a string.
You must select only question column. Try this way:
#Query("SELECT question FROM questions WHERE question_heat = :heat AND question_gender = :gender ORDER BY RANDOM() LIMIT 1")
String getQuestion(int heat, int gender);
You select 3 columns and expect to get a string?
I think you must do this :
#Query("SELECT * FROM questions WHERE question_heat = :heat AND question_gender = :gender" +
" ORDER BY RANDOM() LIMIT 1")
QuestionEntity question(int heat, int gender);
and then convert it manually in repository with
String result = question.getQuestion + question.getQuestionHeat + question.getQuestionGender ;
This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 6 years ago.
I have this app which gets users data from the database using the username they logged in with. The user name is passed once they login to the page which retrieves their account information. The app crashes saying retrieving the information was wrong, can anyone help?
The database code
public Cursor RetriveLoggedUsersData (DatabasOpperations DBOpp, String Username){
SQLiteDatabase SQDB = DBOpp.getReadableDatabase();
String[] Coloumns = {TableData.TableInfo.FIRSTNAME, TableData.TableInfo.LASTNAME, TableData.TableInfo.EMAIL, TableData.TableInfo.USERNAME, TableData.TableInfo.PASSWORD, TableData.TableInfo.IMAGE};
String Where = TableData.TableInfo.USERNAME + " LIKE ?";
String Argument[] = {Username};
Cursor Cur = SQDB.query(TableData.TableInfo.TABLE_NAME, Coloumns, Where, Argument, null, null, null);
Log.d("DatabaseOperations", "Success, User Retrived");
return Cur;
}
The code which wants to retrieve the data
Username = getIntent().getExtras().getString("Username");
DatabasOpperations DB = new DatabasOpperations(Contx);
Cursor Cur = DB.RetriveLoggedUsersData(DB, Username);
DBFName = Cur.getString(0);
DBLName = Cur.getString(1);
DBEmail = Cur.getString(2);
You need to move the Cursor to the first position by making a call to moveToFirst(), and also check the return value to make sure there is at least one row in the Cursor. Also be sure to close your Cursor:
Cursor Cur = DB.RetriveLoggedUsersData(DB, Username);
if (Cur.moveToFirst()) {
DBFName = Cur.getString(0);
DBLName = Cur.getString(1);
DBEmail = Cur.getString(2);
}
Cur.close();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm having a hard time exactly visualizing 'Cursor' functionality in my program. I kind of get the jist of it, but can anyone explain it's functionality in detail?
By Cursor, I mean the Cursor interface.
I can't simply understand the role it plays with anything.
http://developer.android.com/reference/android/database/Cursor.html
A Cursor object is returned from a query on a SQLite database.
It will return all rows that the query returns.
Say you have a table called names in your database database configured as such:
_id _name
1 Space Ghost
2 Zorak
3 Moltar
4 Brak
If you want to get all data from this table and use it, you would do
something like this:
public HashMap<Integer, String> getNames(){
HashMap<Integer, String> data = new HashMap<Integer, String>();
try{
SQLiteOpenHelper helper = new MyOpenDbHelper(context);
SQLiteDatabase db = helper.getReadableDatabase();
String selectQuery = "SELECT * FROM names";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()){ //make sure you got results, and move to first row
do{
int mID = cursor.getInt(0); //column 0 for the current row
String mName = cursor.getString(1); //column 1 for the current row
data.put(mID, mName);
} while (cursor.moveToNext()); //move to next row in the query result
}
} catch (Exception ex) {
Log.e("MyApp", ex.getMessage());
} finally
{
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
return data;
}
Usually you will create your own class to extend SQLiteOpenHelper, as such:
public class MyOpenDbHelper extends SQLiteOpenHelper {
//........
}
From Wikipedia
In computer science, a database cursor is a control structure that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. The database cursor characteristic of traversal makes cursors akin to the programming language concept of iterator.
From Here
A cursor is a tool that allows you to iterate the records in a set. It has concepts of order and current record.
From The documentation you pointed yourself
provides random read-write access to the result set returned by a database query.
So don' t think Cursor as a functionality, but as a mean for reaching records in a more efficient way from any database.
Are you reffering to this Cursor usage?
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
I have a problem with to update a varchar in the sqlite database in java.
when I run this source, than I get a error.
I want String a to update to String b.
This is my source:
public void onClick (View v){
String a = "Test1";
String b = "Test2";
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, a, null);
db.close();
}
And this is my Error:
Error updating Level1=Test2 using update Game SET Level1=? WHERE Test1.
can someone help me?
Thanks!
I'm not 100% sure what you are trying to achieve, however, you added a as a where clause and did not provide any arguments, so consequently you got the SQL statement shown in the error.
From the API:
public int update (String table, ContentValues values,
String whereClause, String[] whereArgs)
This one works ...
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, "Level1=?", new String[] {a} );
db.close();
... if this is the resulting SQL you want to execute:
update Game SET Level1=? WHERE Level1 = 'Test1'
update Game SET Level1=? WHERE Test1.
Where Test1 is.. what? Where is the conditional part of your update statement. It's expecting something like:
update Game SET Level1=? WHERE ColumnName='Test1'
Taken from this website:
If the UPDATE statement does not have a WHERE clause, all rows in the table are modified by the UPDATE. Otherwise, the UPDATE affects only those rows for which the result of evaluating the WHERE clause expression as a boolean expression is true.
A String on it's own is in no way a boolean expression.