Hi i'm new to android programming and i have created a sample app which allows the user to get data from the database. however its not displaying the data, it doesn't have any error message its just not displaying it. database is confirmed that there is data. please check my code maybe i forgot something here. thanks
public void onClick(View arg){
name = txtNameS.getText().toString();
if(arg.getId()==R.id.btnfortune){
searchRecord(count);
lblmessageS1.setText(name); // this is just for me to check if it will be displayed and it is.
lblmessageS2.setText(message);
}
}
public void searchRecord(int count) throws SQLException {
Cursor rsCursor;
String [] rsFields = {"mesNum","Message"};
rsCursor = dbM.dbase.query("MessageFile", rsFields, "mesNum = " + count, null, null, null, null, null);
rsCursor.moveToFirst();
if (rsCursor.isAfterLast()==false){
message = rsCursor.getString(1);
}
rsCursor.close();
}
by the way count is initialized as 1. and there are 10 records in the database. and there are 2 columns in the database the mesNum and Message, what i want is to display only the message column.
// SQLiteDatabase sqldb
Cursor rsCursor= sqldb.rawQuery("your query", null);
if (rsCursor!= null) {
if (rsCursor.moveToFirst()) {
do {
// do here for get data message = rsCursor.getString(1);
}while (cursor.moveToNext());
}
cursor.close();
}
add only one column name in your array
String [] rsFields = {"Message"};
cursor = dbM.dbase.query(true,"MessageFile", rsFields, "yourcolumn= "+count, null, null, null, null, null);
while( cursor != null && cursor.moveToNext() )
{
cursor.getString(0);
}
cursor.close();
Related
I am creating app in which i register user and store user's information in database,so i have created database and storing value in databse but i don't know how to fetch data from database and show in textview?Using below query to fetch data but it has error.What is correct way?
public void insertEntry(String fname, String lname, String gen,String weight)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("firstname", fname);
values.put("lastname", lname);
values.put("gender", gen);
values.put("weight",weight);
}
public Cursor fetchData()
{
SQLiteDatabase mDB = dbHelper.getWritableDatabase();
return mDB.rawQuery("SELECT * FROM Register WHERE firstname=? lastname =?" , null);
}
Using this to set fetched value on textview in different activity
Cursor name = sqliteDataBase.fetchData();
tv_name.setText((CharSequence) name);
Try this,
try {
SQLiteDatabase mDB = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM Register WHERE firstname= "+first+" lastname =" + last + ";";
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
String firstName = cursor.getString(cursor.getColumnIndex("firstname")));
}
}
} catch(Exception e) {
e.printSTackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
public String fecthResults()
{
String name = null;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
name = cursor.getString(cursor.getColumnIndex("firstname")
} while (cursor.moveToNext());
cursor.close();
}
sqLiteDatabase.close();
return name;
Get the name and then set it directly to a texView
A Cursor is an interface that provides random read-write access to the result set returned by the query. It contains multiple rows of data and this data can be easily processed by help of For loop.
Lets take an example to understand the process. Suppose, you need to access data from a column name "col_1" and show the data in TextView. The For loop for the process will be as follows.
for (cursor.moveToNext()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Now, if we need only one value (from only one record or tuple) then, we can opt out the For loop and change the code as shown below.
if (cursor.moveToFirst()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Always remember to close the cursor after using it.
To close the cursor, use the following line of code.
cursor.close();
For more information, please visit the following links:
https://developer.android.com/reference/android/database/Cursor.html
https://developer.android.com/training/basics/data-storage/databases.html#ReadDbRow
public String[] getNewsLink(String prodcuttye) {
Cursor cursor = mDb.query(SQLITE_TABLE, new String[] { "productname" }, "ProdctType='"
+ prodcuttye + "'", null, null, null, null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
result[i] = cursor.getString(cursor.getColumnIndex("productname"));
i++;
} while (cursor.moveToNext());
}
if ((cursor != null) && !cursor.isClosed()) {
cursor.close();
mDb.close();
}
return result;
}
This function for fetch data in String array i am trying to excute this Query am getting data when i am call the in Sqlite browser[ select productname from MyShopingTable where ProdctType= 'Basmati Rice'] But when i try to run this Query in function i am getting cursor count 0 so i am unable to get data please tell me where am doing wrong please suggest me
Try changing your query like following :
Cursor c = mDb.query("SELECT * FROM MyShopingTable where ProdctType = ?",new String[]{prodcuttye})
See if that works in your case...
what is wrong with this code
when i run it the program don,t response
public Cursor checkauth(String username,String password)
{
Ecommerce=getReadableDatabase();
// Cursor curser =Ecommerce.rawQuery("select * from customer where username = ? and password =?", new String []{username,password});
//String [] details={"id","custname","gender"};
Cursor c = Ecommerce.rawQuery("select id from customer where username = ? AND password = ?" , new String[] {username,password });
//Cursor cursor = Ecommerce.query(true, "customer",details,"username = ? AND password = ?", new String[] { username, password },null, null, null, null, null);
while(c != null)
{
c.moveToFirst();
}
return c;
}
in activity
public void onClick(View arg0) {
// TODO Auto-generated method stub
user_name=username.getText().toString();
passwords=password.getText().toString();
Cursor c=data.checkauth(user_name, passwords);
while(!c.isAfterLast())
{
username.setText(String.valueOf(c.getInt(0)));
c.moveToNext();
}
}
![enter image description here][1]
You're blocking your UI thread.
This loop never completes:
while(c != null)
{
c.moveToFirst();
}
The while condition is always true. The loop doesn't seem to be doing anything useful, you can probably just leave a plain c.moveToFirst() there.
Try with this..
String selectQuery = "Write select query" ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
boolean result = false;
if (cursor.moveToFirst())
{
do
{
result = true;
} while (cursor.moveToNext());
}
else
{
result = false;
}
Even though this question is answered already, I'd like to suggest a simple improvement. What you're doing is kind of useless. Your goal is to know whether or not a user exists and what his or her id is.
public int checkAuth(String username, String password) {
String sql = "select id from customer where username = ? AND password = ?";
Ecommerce = getReadableDatabase(); //field names never start with uppercase
Cursor c;
try {
c = Ecommerce.rawQuery(sql, new String[] { username, password });
if (c.moveToFirst()) //if the cursor has any records, this returns true, else false
return c.getInt(0); //so if a user exists with given params, we can return an id
else
return -1; //if not, we return -1, which means: user/pass-combination not found
}
finally { //but after the whole method, we need to do some things:
if (c != null && !c.isClosed())
c.close(); //close the cursor
closeDatabase(); //and close the database
}
}
This way you keep your UI code separated from your database code. A cursor shouldn't appear in UI-code. Which above modifications, the UI code looks a lot cleaner
int i = data.checkAuth(username, password);
if (i == -1) {
//alert of some kind
}
else
username.setText(String.valueOf(i));
I have been trying to get all rows from the SQLite database. But I got only last row from the following codes.
FileChooser class:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
fileName.add(cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1)));
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
FileSQLiteAdapter class:
public Cursor queueAll() {
String[] columns = new String[] { KEY_ID, KEY_CONTENT1 };
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null,
null, null, null, null);
return cursor;
}
Please tell me where is my incorrect. Appreciate.
try:
Cursor cursor = db.rawQuery("select * from table",null);
AND for List<String>:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Using Android's built in method
If you want every column and every row, then just pass in null for the SQLiteDatabase column and selection parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);
More details
The other answers use rawQuery, but you can use Android's built in SQLiteDatabase. The documentation for query says that you can just pass in null to the selection parameter to get all the rows.
selection Passing null will return all rows for the given table.
And while you can also pass in null for the column parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says
columns Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
MyDatabaseHelper.COLUMN_1,
MyDatabaseHelper.COLUMN_2,
MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
null, null, null, null, null);
This is almost the same solution as the others, but I thought it might be good to look at different ways of achieving the same result and explain a little bit:
Probably you have the table name String variable initialized at the time you called the DBHandler so it would be something like;
private static final String MYDATABASE_TABLE = "anyTableName";
Then, wherever you are trying to retrieve all table rows;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + MYDATABASE_TABLE, null);
List<String> fileName = new ArrayList<>();
if (cursor.moveToFirst()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
while(cursor.moveToNext()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
}
}
cursor.close();
db.close();
Honestly, there are many ways about doing this,
I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
name = cursor.getString(cursor
.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Update queueAll() method as below:
public Cursor queueAll() {
String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
return cursor;
}
Update readFileFromSQLite() method as below:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do
{
String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
fileName.add(name);
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
Cursor cursor = myDb.viewData();
if (cursor.moveToFirst()){
do {
String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));
}while (cursor.moveToNext());
}
cursor.requery();
public List<String> getAllData(String email)
{
db = this.getReadableDatabase();
String[] projection={email};
List<String> list=new ArrayList<>();
Cursor cursor = db.query(TABLE_USER, //Table to query
null, //columns to return
"user_email=?", //columns for the WHERE clause
projection, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null);
// cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(cursor.getColumnIndex("user_id")));
list.add(cursor.getString(cursor.getColumnIndex("user_name")));
list.add(cursor.getString(cursor.getColumnIndex("user_email")));
list.add(cursor.getString(cursor.getColumnIndex("user_password")));
// cursor.moveToNext();
} while (cursor.moveToNext());
}
return list;
}
a concise solution can be used for accessing the cursor rows.
while(cursor.isAfterLast)
{
cursor.getString(0)
cursor.getString(1)
}
These records can be manipulated with a loop
I've been playing with a sample application I found online. Just changing things to see how it works. Yesterday this was not an issue. Today is a different story. I seem to write the correct info to the db. I've checked through log outputs. When I return the information through a cursor I get "null". So, say I enter "Eggs","Bread", and "Candy". I get back "null","null", and "null".
It all starts with the listener for the add grocery button. Adds to the db and writes the list to an label.
Any help?
private void addEvent(String title) {
SQLiteDatabase db = eventsData.getWritableDatabase();
ContentValues values = new ContentValues();
Log.v(TAG, "Adding " + title);
values.put(EventsDataSQLHelper.TITLE, title);
db.insert(EventsDataSQLHelper.TABLE, null, values);
}
private Cursor getEvents() {
SQLiteDatabase db = eventsData.getReadableDatabase();
Cursor cursor = db.query(EventsDataSQLHelper.TABLE, null, null, null, null,
null, EventsDataSQLHelper.TITLE);
startManagingCursor(cursor);
return cursor;
}
private void showEvents(Cursor cursor) {
StringBuilder ret = new StringBuilder();
while (cursor.moveToNext()) {
String title = cursor.getString(1);
ret.append(title + "\n");
Log.v(TAG, "SHOWING RET VARIABLE" + ret);
}
t.setText(ret);
}
View.OnClickListener myhandler = new View.OnClickListener()
{
#Override
public void onClick(View GLview)
{
EditText eT = (EditText)findViewById(R.id.itemName1);
editTextStr = eT.getText().toString();
Log.v(TAG, editTextStr);
if(editTextStr != null)
{
addEvent(editTextStr.toString());
Cursor cursor = getEvents();
showEvents(cursor);
eT.setText(null);
}
}
};
Make sure cursor points to the first element of the result cursor.moveToFirst();
Then call cursor.moveToNext()