How to retrieve row data from SQL database - Android - android

I add data into a database using this code,
/**
* Storing deck
* */
public void addDeck(String id, String name, String uid, String did) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_DECK_ID, id); // ID
values.put(KEY_DECK_NAME, name); // Name
values.put(KEY_DECK_UID, uid); // Unique Id
values.put(KEY_DECK_DID, did); // Deck id
// Inserting Row
db.insert(TABLE_DECK, null, values);
db.close(); // Closing database connection
}
Now I want to be able to access each row, how can I do this?
This is my current code to access the rows in the database
// Getting deck data from database
public HashMap<String, String> getDeckDetails(){
HashMap<String,String> deck = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_DECK;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
deck.put("id", cursor.getString(1));
deck.put("name", cursor.getString(2));
deck.put("uid", cursor.getString(3));
deck.put("did", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return deck;
}
This code only returns the first row, how can I get it to return every row?

you have to use a loop:
Cursor cursor = db.rawQuery(selectQuery, null);
while( cursor.moveToNext() ){
deck.put("id", cursor.getString(1));
deck.put("name", cursor.getString(2));
deck.put("uid", cursor.getString(3));
deck.put("did", cursor.getString(4));
}
cursor.close();
also, instead of cursor.getString(3) I'd use:
int uidPos = cursor.getColumnIndex( "uid" );
if( -1 != uidPos ) cursor.getString( uidPos );
as it's safer

Related

Fetch data from Sqlite database

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

SQLite exception- unrecognized token when trying to update table

I am trying to update my SQLite database through this method in my SQLiteHelper class and I am getting the error:
android.database.sqlite.SQLiteException: unrecognized token: "55c7e253afcf48" (code 1): , while compiling: UPDATE login SET user_group=? WHERE uid=55c7e253afcf48.85187730
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
The uid is correct other than the extra ".85187730" at the end... I'm not sure what those numbers mean.
Here is my update method:
//updating sqlite database with the group name
public void updateUserGroup(String groupName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_GROUP, groupName);
HashMap<String, String> user = getUserDetails();
String userID = user.get("uid");
System.out.println("User id is: " + userID);
db.update(TABLE_LOGIN, values, SQLiteHandler.KEY_UID + "=" + "userID", null);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("user_group", cursor.getString(3));
user.put("uid", cursor.getString(4));
user.put("created_at", cursor.getString(5));
}
cursor.close();
//db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
Any help is appreciated.
You've missed quotation marks around your uid.
You should pass every string as below to avoid errors.
UPDATE login SET user_group=? WHERE uid="55c7e253afcf48.85187730"
and in your case query will be like
HashMap<String, String> user = getUserDetails();
String userID = user.get("uid");
db.update(TABLE_LOGIN, values, SQLiteHandler.KEY_UID + "=\"" + userID + "\"", null);

Is it possible to get both Interger and String value from one HashMap method?

I want to merge my two Hashmap methods. One method is for getting user ID and the other is for getting user String information. But I want to get all information from one hashmap method. Is it possible? If it is, how can I do this in my getuserdetails hashmap method?
Method 1:
public HashMap<String, Integer> getUid() {
HashMap<String, Integer> uid = new HashMap<String,Integer>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
Log.d("database", "before uid put");
if (cursor.getCount() > 0) {
uid.put("uid",cursor.getInt(0));
}
cursor.close();
// return user
return uid;
}
Method 2:
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("created_at", cursor.getString(3));
}
cursor.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
The cleanest approach here would be to create a User object with fields for id, name, email and created_at, something like this:
public class User {
private int id;
private String name;
private String email;
private Date createdAt; // Or use string here, whichever you want
// create or generate getters and setters for above fields
}
You can then get the data from the database using your query and create a user:
public User getUserDetails() {
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
User user = new User();
if (cursor.getCount() > 0) {
user.setId(cursor.getInt(0));
user.setName(cursor.getString(1));
user.setEmail(cursor.getString(2));
user.setCreatedAt(cursor.getString(3));
}
else {
cursor.close();
return null; // There wasn't a user to be found
}
cursor.close();
return user;
}
Now your method creates a User object, containing all required information.
Make a class with uid and name veriable And Create a hashmap method as a return type of this class. Hope this will work.
you can wrap together in a class like
public class Info {
public int uid;
public String name;
}
and have a HashMap<String, Info>

cannot able to insert more than one row in android SQLite DB

I am working on a project where 6 edittext fields are inserted into the the database when i click the save button and it will be viewed in a list... I can able to achieve those things but problem is that i could not able to insert multiple rows into the DB. The listview is showing only the first inserted values always eventhough if i insert again. Please help me for this solution.... My code for table creation and insertion is as follows for your reference
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE_QUERY = null;
// Used
CREATE_TABLE_QUERY = "CREATE TABLE IF NOT EXISTS userMaster(Bar CHAR(25),Product CHAR(15), Name TEXT,Mrp CHAR(15),Quantity CHAR(15), Tax CHAR(15));";
db.execSQL(CREATE_TABLE_QUERY);
L.i("userMaster Table created");
}
public void insertDetails(String bar, String mrp, String quantity,
String tax, String product, String name) {
SQLiteDatabase dbase = this.getReadableDatabase();
ContentValues cv = new ContentValues();
cv.put("bar", bar);
cv.put("product", product);
cv.put("name", name);
cv.put("mrp", mrp);
cv.put("quantity", quantity);
cv.put("tax", tax);
dbase.insert("userMaster", null, cv);
dbase.close();
} <br>
public void insertUserMaster(String bar, String mrp, String quantity,
String tax, String product, String name) {
SQLiteDatabase SqlDB = getWritableDatabase();
SqlDB.delete("userMaster", null, null);
String INSERT = "insert into userMaster (Bar,Product,Name,Mrp,Quantity,Tax) values (?,?,?,?,?,?)";
SQLiteStatement insertstatment = SqlDB.compileStatement(INSERT);
insertstatment.bindString(1, bar);
insertstatment.bindString(2, product);
insertstatment.bindString(3, name);
insertstatment.bindString(4, quantity);
insertstatment.bindString(5, mrp);
insertstatment.bindString(6, tax);
insertstatment.executeInsert();
SqlDB.close();
close();
} <br>
The array list representation is as follows
public ArrayList<HashMap<String, String>> getdata() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query("userMaster", null, null, null, null, null,
null, null);
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
if (cursor != null) {
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
do {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("bar", cursor.getString(0));
hm.put("product", cursor.getString(1));
hm.put("name", cursor.getString(2));
hm.put("mrp", cursor.getString(3));
hm.put("quantity", cursor.getString(4));
hm.put("tax", cursor.getString(5));
arraylist.add(hm);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return arraylist;
}
Use proper query to avoid those issue. Before inserting check whether you are deleting the existing table..
In method insertUserMaster you delete all data before insert.
Remove this line:
SqlDB.delete("userMaster", null, null);

My android sqlite database app gets close when I search the name which does not exist in the table

Here is a code/method to find if some name exists in the table or not..
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
I already have a function to get all names in an arrayList. I can call it before calling the above function to solve my problem. But I want to ask about is there any other (straight) way to do it
When you call cursor.moveToFirst() it will return true if there is a valid result there, or false in the case no results are found. If cursor.moveToFirst() returns false, then calling any of the getXXX() methods will fail.
Try something like this:
if( cursor.moveToFirst() )
{
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
}
cursor.close();
Note that the Cursor returned from SQLiteDatabase.query is guaranteed to be non-null.
if (cursor == null)
Toast.makeText(getApplicationContext(), "No Records Exist", Toast.LENGTH_SHORT).show();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if(cursor.moveToFirst()){
do {
Double lat = cursor.getDouble(2);
Double lon = cursor.getDouble(1);
} while (trackCursor.moveToNext());
}
Here is a code for getting all the contacts in a list from the table...
/**
* Getting all the contacts in the database
*/
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return contactList;
}
Then it is invoked in another function that returns "true" if name is present in the table "false" otherwise...
/**
* checks if name already present in the database
* #param name
* #return
*/
public boolean checkDbData(String name){
List<Contact> contactList =getAllContacts();
boolean checkName = false ;
for(Contact cn: contactList){
String dbName = cn.getName();
if(name.equals(dbName)){
checkName = true ;
}
}
return checkName;
}
And if this function returns "true", then the above given function is invoked to get the contacti.e.
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
Note: we can also get this contact from the contactList, both can be used to get the required contact (i.e. "name" in this case)

Categories

Resources