How to retrieve data from database table by Username? - android

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 ..!

Related

SQLite select query returning null when it shouldn't

I'm getting a null pointer exception on the following line of code
attendanceList = dbHelper.getAttendance(surName, name);
both surName and name are not null, have size() > 0 and attendanceList is of type ArrayList and here is the getAttendance function:
public ArrayList<Attendance> getAttendance(String surName, String name)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Attendance> attendanceList = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + ATTENDANCE_TABLE + " WHERE " + COLUMN_SURNAME + " =? AND "
+ COLUMN_NAME + " =?", new String[] {surName, name});
if(cursor .moveToFirst())
{
while(!cursor.isAfterLast())
{
Attendance attendance = new Attendance();
attendance.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_DATE)));
attendance.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
attendance.setSurName(cursor.getString(cursor.getColumnIndex(COLUMN_SURNAME)));
attendance.setState(cursor.getString(cursor.getColumnIndex(COLUMN_STATE)));
attendance.setTerm(cursor.getInt(cursor.getColumnIndex(COLUMN_TERM)));
attendance.setSubject(cursor.getString(cursor.getColumnIndex(COLUMN_SUBJECT_NAME)));
attendanceList.add(attendance);
cursor.moveToNext();
}
cursor.close();
db.close();
return attendanceList;
}
else
{
cursor.close();
db.close();
return null;
}
}
There is no syntax error in the above function, and I know it shouldn't return null because I see the content of the ATTENDANCE_TABLE using DB Browser for SQLite. Can someone point what is wrong with my code? I feel like I wrote 1 + 1 = 2 and getting an error..
Try this... SQLiteDbHelper is my DataBase Class where my table is defined. Table_Name is string in which my table name is stored
cursor = db.rawQuery("SELECT * FROM "+SQLiteDBHelper.TABLE_NAME+" WHERE "+SQLiteDBHelper.COLUMN_SURNAME+"=? AND "+SQLiteDBHelper.COLUMN_NAME+"=?",new String[] {surName,name});
if (cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
//Retrieving User SurName and Name
String s_name = cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_SURNAME));
String _name= cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_NAME));
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
I am pretty sure that it not surName or name that causes NullpointerException, but dbHelper is.
So please check if you are initialising your dbHelper after this line
attendanceList = dbHelper.getAttendance(surName, name);
If so, then move it above and your crash will be fixed.
Hope it helps.

Retrieving specific data based on ID from SQLite in ANDROID

I wrote a code in which i can retrieve the data from the database but when i run it and try to search something. The application crashes as soon as i press Submit
public class search extends AppCompatActivity {
Button SearchButton;
EditText SearchText;
TextView SearchResult;
SQLiteDatabase db;
String builder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
SearchButton=(Button)findViewById(R.id.searchbutton);
SearchText=(EditText)findViewById(R.id.Searchtext);
SearchResult=(TextView)findViewById(R.id.SearchCourse);
db=this.openOrCreateDatabase("Courses", Context.MODE_PRIVATE,null);
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int GetID = Integer.valueOf(SearchText.getText().toString());
Cursor TuplePointer = db.rawQuery("Select from Course where ID="+GetID+"",null);
TuplePointer.moveToFirst();
String Course = TuplePointer.getString(TuplePointer.getColumnIndex("Course"));
SearchResult.setText(Course);
}
});
}
}
Replace this line
Cursor TuplePointer = db.rawQuery("Select from Course where ID=" + GetID + "", null);
with
Cursor TuplePointer = db.rawQuery("Select Course from Course where ID=" + GetID + "", null);
Where Course is your column name
Write your code within try catch first. Afterthat try to catch exact exception. you will be clear what are you doing wrong.
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " Where " + KEY_APP_BOOKINGID + " = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
Please Try this
SQLiteDatabase db = this.getReadableDatabase();
String GetID = SearchText.getText().toString();
Cursor cursor = db.rawQuery("SELECT * FROM Course WHERE ID = ?", new String[]{String.valueOf(GetID)}, null);
if (cursor.moveToFirst()) {
do {
String Course = cursor.getString(cursor.getColumnIndex("Course"));
SearchResult.setText(Course);
} while (cursor.moveToNext());
}
Thank You everyone I figured out what i was doing wrong on the get Column index i targeted course but what i didnt realize is that there was no such field as course :)
Keep practice like below code you will debug proper
public void getFirstName(String id) {
String sql = "select first_name from basic_info WHERE contact_id="+ id;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
Log.e("Result =>",FirstName);
}
c.close();
}
return data;
}
public Cursor fetchData(String sql) {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(sql, null);
}

SQLite Query to Get Column Data

Using following query to get column data:
public String getR(String str) {
String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";
return strR;
}
In Activity, I am trying to read returned strR :
String string = mydb.getR("1400");
Toast.makeText(SyncAll.this, string, Toast.LENGTH_SHORT).show();
But in Toast, I am getting my Select query itself instead of Record, like this:
SELECT col_no FROM tracking where col_id = '1400' ORDER BY col_no DESC LIMIT 1
May I know ! Where I am doing mistake ?
I tried the same way suggested by prosper k above, and finally got the solution:
public String getR(String str) {
String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(strR, null);
if (cursor != null)
cursor.moveToFirst();
strR = cursor.getString(0);
return strR;
}
You're calling the function getR, which is returning the string value strR.
I'm assuming that mydb is an extended object from class SQLiteOpenHelper, and that you have followed the documentation here https://developer.android.com/training/basics/data-storage/databases.html then you'll have to execute the query like:
Cursor cursor = null;
try {
SQLiteDatabase db = this.getWritableDatabase();
synchronized(this) {
cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
col_no = cursor.getInt(0);
}
}
} finally {
if (null != cursor)
cursor.close();
}
return col_no;

getting exception while checking for valid username and password in sqlite

I'm trying to check for a valid user. But I'm getting the following Exception:
no such column: ABC(Code 1):, while compiling: SELECT _id, username, password
FROM MyTable1 WHERE username=ABC
The code is as follows:
public int checkUser(String userName, String password) {
int check = -1;
int id = 2;
String psword = new String();
Cursor cursor = database.query(TABLE_NAME, allColumns, COLUMN_USER_NAME + "=" + userName, null, null, null, null);
cursor.moveToFirst();
Log.v(TAG, "After CURSOR!!");
psword = cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD));
Log.v(TAG, "pasword: " + psword);
if (psword.equals(password)) {
check = 1;
}
return check;
}
What am I doing wrong?? Please help
If username is varchar/text type then
Cursor cursor = database.query(TABLE_NAME, allColumns, COLUMN_USER_NAME
+ "=" + '"+userName+"', null, null, null, null);
This is sample login function
public boolean checkUser(String username, String password) throws SQLException
{
String whereClause = " USERNAME = '"+userName+"' ";
try {
open();// dbopen
Cursor cursor = db.query(TABLE_NAME, allColumns,whereClause, null, null, null, null);
}catch(Exception e){
}
}
or
public boolean checkUser(String username, String password) throws SQLException
{
Cursor mCursor = database.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE username=? AND password=?", new String[]{username,password});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
You should add quotes around userName. You want the rows that match the string value "ABC" or 'ABC' I don't remember which quotes. If you don't put quotes you are matching with the column named ABC.
And you should use prepares statements instead. That would avoid you many problems.

cursor index out of bounds "index 0 requested: with size 0"

I am getting cursor index out of bounds "index 0 requested: with size 0" error when I search my database for something. The item I am searching for in my database does not exist currently and i am aware of that but how do i handle a query where the item does not exist.
i send in a phone number
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.getIdFromPhone(number);
String test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
curs.close();
db.close();
return test;
}
query
public Cursor getIdFromPhone(String where){
Cursor cur = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + where + "'",null,null,null,null);
if(cur != null)
cur.moveToFirst();
return cur;
}
test search
from = messages.getDisplayOriginatingAddress();
String dbNumber = searchNumber(arg0,from);
if(dbNumber.equals(from)){
//do stuff
}else{
//do other stuff
}
if number is not found it should do the else statement but it does not get that far
Cursor.moveToFirst() returns false if the Cursor is empty. The returned Cursor from the query() call will never be null but it might be empty. You are never checking if the cursor is empty.
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + number + "'",null,null,null,null);
String test = null;
if(curs.moveToFirst()) { //edit
test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
}
curs.close();
db.close();
return test; // this will be null if the cursor is empty
}
And get rid of the getIdFromPhone() method.
While you retrive value you have to use cursor.moveToNext;
if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("data"));
// do what ever you want here
}while(cursor.moveToNext());
}

Categories

Resources