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
Related
I'm trying to get the value or data from the array that doesn't exists in the database.
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","cold"};
SQLiteDatabase db= getReadableDatabase();
String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")";
c=db.rawQuery(query,null);
Log.i("From Cursor","Cursor Count : " + c.getCount());
if(c.getCount()>0){
String val= c.getString()
Log.i("From Cursor","No insertion");
}else{
Log.i("From Cursor","Insertion");
}
db.close();
return c;
}
public static String toArrayRep(String[] in) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < in.length; i++) {
if (i != 0) {
result.append(",");
}
result.append("'" + in[i] + "'");
}
return result.toString();
}
In the String values={"headache","cold"} ,headache exists but cold does not exist in the database. From the code above, the Cursor returns Count=1 which is count>0 hence i can't insert into table.I would like to know how i can independently check whether the individual data exists, and the one which doesn't exist will be inserted into table.So in this case, "Cold" would be able to be inserted into the table.
If you use a single query to check all values, then what you get is a list of existing values, and you still have to search in the original list for any differences.
It is simpler to check each value individually:
String[] values = { "headache", "cold" };
SQLiteDatabase db = getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You need check Cursor.moveToFirst()
True = Have records in cursor.
False = Dont have records.
Example my code:
return database.query( table.getNameTable(),
table.getColumns(),
table.getWhereSelectTableScript(),
null,
table.getGroupBySelectTableScript(),
table.getHavingSelectTableScript(),
table.getOrderBySelectTableScript(),
table.getLimitRecordsSelectTableScript());
See more here !
I'm not too sure whether it's appropriate that using 'username' as my selection to retrieve other data instead of using an id. FYI, my username is unique as there will not be any other user having the same username. I'm doing this way because I'm not sure how to use or call the id from the table.
I'm getting this error:
CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
I have a DatabaseAdapter.java with this code:
public Cursor getData(String username){
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cur = db.query(TABLE_PROFILE, COLUMNS_PROFILE, " username=?", new String[]{username}, null, null, null, null );
if (cur != null){
cur.moveToFirst();
}
return cur;
}
With a EditProfileFragment.java:
dbAdapter = new DatabaseAdapter(getActivity());
dbAdapter = dbAdapter.open();
un = getArguments().getString("username");
Cursor cur = dbAdapter.getData(un);
String password = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_PASSWORD));
String age = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_AGE));
String weight = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_WEIGHT));
String height = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_HEIGHT));
String gender= cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_GENDER));
I'm getting the String un in my log, means my username is successfully passed. I'm blur with the data retrieving data from the cursor, please help and thank you in advance for the help.
Try this Answer
public Cursor getData(String username){
SQLiteDatabase db = dbHelper.getReadableDatabase();
String sql="select * from " + tableName + " where username =?";
Cursor cursor=database.rawQuery(sql,new String{username});
if (cursor != null)
{ cursor.moveToFirst();}
return cursor;
}
Hope this will help you
Here is small piece of code.Here i am verifying if user exist or not based on username/email and password.I know it is not complete solution but can guide you in right direction (somehow).
public boolean verifyLogin(String email,String password)
{
Cursor mCursor = ourDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE_USERS + " WHERE Email=? AND Password=?", new String[]{email,password});
if (mCursor != null)
{
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
EditText username;
String S;
S = username.getText().toString();
now run this query
String selectQuery = "SELECT* FROM **TABLE NAME** WHERE username=S ";
Cursor c = db.rawQuery(selectQuery, new String[] { username });
if (c.moveToFirst()) {
temp_address = c.getString(0);
}
c.close();
String name;
name = username.getText().toString();
"select * from yourTable where username= '"+name+"'"
Run this query. I hope it will help you ..!
I have created an application to insert data to sq-lite . i want if i enter same data again it should give e toast massage and then it only update that data not re-insert.
what should i do.....
now data is been re-inserted
method code of SQLiteOpenHelper.....
public void insertdata(String name,String ph,String area){
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
sd=this.getWritableDatabase();
sd.insert("location", null, cv);
sd.close();
method use in Activity class......
public void onClick(View v) {
// TODO Auto-generated method stub
help=new MyHelper(getApplicationContext());
help.getWritableDatabase();
String myname=name.getText().toString();
String call=phone.getText().toString();
String myarea=area.getText().toString().trim();
help.insertdata(myname, call, myarea);
Toast.makeText(getApplicationContext(), "data saved ", Toast.LENGTH_SHORT).show();
}
});
The data is being reinserted because you're methods never check to see if it already exists in the databse. You need to add a query for some unique combination - probably name and phone number. If that query returns a result you can prompt the user to enter the data.
String query = "SELECT * FROM " + TABLE_NAME + " WHERE name = " + name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor != null && cursor.moveToFirst()){ //if cursor has entry then don't reinsert
//prompt user with dialog
} else {
//insert data
}
Also you cannot use a Toast for this. What you want is a Dialog. If the data exists you can display a custom Dialog to the user that you could use to allow them to (1) enter new data (2) edit existing data (3) choose to reinsert the data they are posting. A Toast will just display a message to them like - "reinserting data". It does not sound like that is the functionalty you want to achieve.
To update the database you can just use an update statment depending on what fields you want to change.
String query = "UPDATE " + TABLE_NAME + " SET";
if(!name.isEmpty(){
query += " name = " + name;
}
if(!phone.isEmpty(){
query += " phone = " + phone;
}
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(CREATE_CONTACTS_TABLE)
I put the if statments in to check for which fields are being changed and add them to the query accordingly. In the alternative you could use something like this
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
While I havnet modified it to fit your example you can see the basic approach. Hhere you can use conditionals to check if values are being supplied, if they are you add them to the ContentVlues list which will update them in the DB.
You can try something like this:
ContentValues values=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
if (db == null) {
db = getWritableDatabase();
}
if (isNameExists(name)) { //check if name exits
id = db.update(TABLE_NAME, values, name + " = ?",
new String[] {name});
} else {
id = db.insert(TABLE_NAME, null, values);
}
public boolean isNameExists(String name) {
Cursor cursor = null;
boolean result = false;
try {
String[] args = { "" + name };
StringBuffer sbQuery = new StringBuffer("SELECT * from ").append(
TABLE_NAME).append(" where name=?");
cursor = getReadableDatabase().rawQuery(sbQuery.toString(), args);
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
} catch (Exception e) {
Log.e("AppoitnmentDBhelper", e.toString());
}
return result;
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();
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