I am creating a user login application . I want to show account information of a user when he logs in in textviews of a layout . Here is the image of a layout .
Here is my code for getting data of a user when he logs in :
public Cursor getUserData(String username){
Cursor UserDataCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER_TABLE_NAME + " WHERE " +
USER_NAME + "='" + username+"'", null);
return UserDataCursor;
Here is the code for retrieving data with that class :
String email2 = cursor.getString(cursor.getColumnIndex("email"));
String name2 = cursor.getString(cursor.getColumnIndex("name"));
String pass2 = cursor.getString(cursor.getColumnIndex("pass"));
String gender2 = cursor.getString(cursor.getColumnIndex("gender"));
String date2 = cursor.getString(cursor.getColumnIndex("date"));
String country2 = cursor.getString(cursor.getColumnIndex("country"));
String reg2 = cursor.getString(cursor.getColumnIndex("reg"));
data+=email2+" "+name2+" "+pass2+" "+gender2+" "+date2+" "+country2+" "+reg2+"\n" ;
cursor.moveToNext();
}
It's giving a null pointer exception . What's the problem here ? How can i fix it ?
I think you're making things much harder for yourself by not using the database adapter pattern.
Take a look here for an example of how to set up more abstraction and error handling for your database:
http://www.devx.com/wireless/Article/40842/1954
It is difficult to verify your code, since it is data-dependent. Your column names could be wrong (or one could be missing). Your data type could be wrong. You might be getting a cursor back with NO rows, which you need to check for.
BTW, are you doing cursor.moveToFirst() before starting?
Also, we don't know what's on line 70, where the error occurred, because line numbers are lost in the posting.
Related
I made an app in eclipse for android where you can fill in a person's information like name, email, adress, etc. In this app I need to include a search-button, which will search for a person that is saved in the database when one or more pieces of information are known. E.g. when I only remember the email-adress of a person who is saved in the database, I need to be able to find that person by searching for a matching email. This is the code I used for doing so:
public Person getPerson(String naam, String adres, String email, String geslacht,
String leeftijd, String geboortedatum){
SQLiteDatabase db= this.getReadableDatabase();
Cursor curs=db.rawQuery("SELECT * FROM personen WHERE name = ? OR adress = ? "
+ "OR email = ? OR gender = ? OR age = ? OR birthday = ?",
new String[]{naam==null?"'":naam, adres==null?"'":adres,
email==null?"'":email, geslacht==null?"'":geslacht,
leeftijd==null?"'":leeftijd, geboortedatum==null?"'":geboortedatum});
if(curs!=null)
curs.moveToFirst();
The reason I changed the args[] when it included a null-value is that otherwise the rawQuery won't work. This code however, does not return the person I was searching for, but it simply returns the very first person in the database.
When simplifying the code by making the query search for a persons name only it actually does return the person with that name:
Cursor curs=db.rawQuery("SELECT * FROM personen WHERE name = ?", new String[]{naam});
if(curs!=null)
curs.moveToFirst();
What is wrong with the first rawQuery and why doesn't it return the person I'm looking for, but simply the first person in the database, whereas the second rawQuery does return the right person?
I guess the problem is with the OR. Could you try AND and see ? Because OR is usually means optional. What i mean by optional is, you are telling sql engine to return the person with any of those attributes it matches too. So you are not restricting but giving many possibility abd OR is ending up with many users and therefore its getting the first one. Dont use OR. Try creating a query that returns a unique result you want.
public Person getPerson(String naam, String adres, String email, String geslacht,
String leeftijd, String geboortedatum){
SQLiteDatabase db= this.getReadableDatabase();
Cursor curs=db.rawQuery("SELECT * FROM personen WHERE name = ? OR adress = ? "
+ "OR email = ? OR gender = ? OR age = ? OR birthday = ?",
new String[]{naam==null?"'":naam, adres==null?"'":adres,
email==null?"'":email, geslacht==null?"'":geslacht,
leeftijd==null?"'":leeftijd, geboortedatum==null?"'":geboortedatum});
if(curs!=null)
if (curs.moveToFirst()){
while(curs.hasNext){
//Your code, this will return all the rows of your sql,use curs.next() to get a row
}
I have make following function for getting data.
public List<Presentation> getSlideMaster() {
List<Presentation> pptList = new ArrayList<Presentation>();
String selectQuery = "SELECT * FROM "
+ Constants.SLIDE_MASTER.slideMaster_Table + " WHERE dm_Id=" + lastDeckID;
SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Presentation presentation = new Presentation();
presentation.setSlideId(cursor.getString(0));
getSlideID = presentation.getSlideId();
Log.i("string slide id in database helper", "" + presentation.getSlideId());
pptList.add(presentation);
} while (cursor.moveToNext());
}
String selectQuery2 = "SELECT sl_Id FROM "
+ Constants.SLIDE_LAYOUT.slideLayout_Table + " WHERE sm_Id = "
+ getSlideID;
Cursor cursorSL = db.rawQuery(selectQuery2, null);
Log.i("query", ""+selectQuery2);
if(cursorSL.moveToFirst()){
Log.i("getslideLayout function", "");
do{
Log.i("query string 0 ", ""+cursorSL.getString(0));
Presentation presentation = new Presentation();
presentation.setSlideLayoutId(cursorSL.getString(0));
getSlideLayoutId = presentation.getSlideLayoutId();
Log.i("string slide layout id in slideMaster", "" + getSlideLayoutId);
}while(cursorSL.moveToNext());
}
else{
Log.i("No Data Found!!!!!", "");
}
cursor.close();
cursorSL.close();
db.close();
return pptList;
}
I getting data from slideMaster_Table very fine and easily but I can't get data from another query, which is not print any value in Logcat inside of if(cursorSL.moveToFirst()) condition
When I use code in another activity i can get sl_Id very easily.
may below solution solve your problem
use Cursor cursorSL = db.rawQuery(selectQuery2, new String[]{getSlideID});
for
selectQuery2="SELECT sl_Id FROM "+Constants.SLIDE_LAYOUT.slideLayout_Table + " WHERE sm_Id = ?";
My speculation is that you have troubles constructing the second query. Basically it is never a good idea to construct database queries like you do. The android database API is providing more accurate interface for that. Rewrite your second part of program to:
String [] selectArgs = {getSlideID};
String selectQuery2 = "sm_Id = ?";
Cursor cursorSL = db.query(Constants.SLIDE_LAYOUT.slideLayout_Table, null,
selectQuery2, selectArgs, null, null, null, null);
Note that the fourth parameter of query is meant for substitution of where arguments, it is String[] and all the array members are substituted in sequence in the places of ? in the query string.
I think you might be facing problem with constructing the query.
PS: You are also misusing the log tags:
Log.i("No Data Found!!!!!", "");
Should actually be Log.i("TAG", "No Data Found!!!!!");
The first parameter is log tag and is supposed to be used for grouping related log messages, in your case you print every message in its own group, which does not make much sense.
I know this note will not solve your immediate problem, but I am pointing it out, so that you will know it for the future (I also suffer from seeing colleagues of mine learning from SO wrong practises like that one).
How to remove bracket around sstirng? I'm geting value from database save in arraystring when run database query its show bracket around value what do I do?
I want to remove bracket around stirng [AT] how to do that?
static ArrayList<String> Meal_groupid = new ArrayList<String>();
String formatedString = "[AT]"
.replace("[", "") //remove the right bracket
.replace("]", "");
Log.i("Formating Stirng",""+formatedString);
Meal_groupid.add(mCursor2.getString(mCursor2.getColumnIndex("meal_group_id"))
.replace("[", "").replace("]", ""));
Log.i("MEalGroup ID",""+Meal_groupid);
when see in logcat
in logcat Formating Stirng AT
MEalGroup ID [AT]
when I run query
Cursor mCursor = db.selectQuery("
SELECT m.menu_id, m.title AS menu_title
FROM uss_school_to_menu sm
LEFT JOIN uss_menu m on sm.menu_id = m.menu_id
LEFT JOIN uss_school s on s.school_id = sm.school_id
WHERE s.school_id = '"+ School_ID+"' AND sm.level_id = " +
SchoolLevelId + " AND m.meal_group_code = '"+Meal_groupid.toString()+"'" );
in database it looks like this
SELECT m.menu_id, m.title AS menu_title
FROM uss_school_to_menu sm
LEFT JOIN uss_menu m on sm.menu_id = m.menu_id
LEFT JOIN uss_school s on s.school_id = sm.school_id
WHERE s.school_id = '147' AND sm.level_id = 1 AND m.meal_group_code = '[AT]'
I want to remove bracket around [AT]
You are calling toString() on your ArrayList<String> to get the string out of it, which won't work. If you call toString() on an ArrayList<T>, you typically get an output of
"[" + get(0).toString() + " " + get(1).toString() + " " + get(2).toString() + etc + "]"
You have only one element, so it ends up looking like brackets were added around your string.
Do you really need an array list here? If so, you need to replace Meal_groupid.toString() with Meal_groupid.get(0), except 0 should be replaced with the index of whichever string in the list you need.
If you only need one string at a time, then avoid using the array list altogether, so you can directly plug the string into your database query.
You don't need .replace("[", "").replace("]", ""), because there are no brackets around your actual string.
Having a confounding problem with a query that worked for a while and then stopped working. With a try and catch, there is no error it just returns a null cursor?
Is there a GUI where you can run the query to check the result first or see an error, perhaps it is something subtle like keys? I have confirmed the data types but don't know where else to look. I have concerns going forward on how to debug this type of issue so would appreciate any direction you can offer.
Thanks in advance.
The code set works fine on a single table but when I join 2 tables it now fails (worked yesterday)
Working:
String selectQuery =
SELECT ou.*,"name" as Orchard_Name FROM " + TABLE_TP_ORCHARD_USER ou ;
not working in this case a joined query :
String selectQuery = "SELECT ou.tp_orchard_user_Orchard_ID as
tp_orchard_user_Orchard_ID,ou.tp_orchard_user_User_ID as
tp_orchard_user_User_ID,sd.Orchard_Name as Orchard_Name FROM " +
TABLE_TP_ORCHARD_USER + " ou JOIN " + TABLE_SD_ORCHARD + " sd on
ou.tp_orchard_user_Orchard_ID=sd.Orchard_Id" ;
I have run this code in mysql on another DB and it is fine; it seems maybe there is another error that eclipse can't display? Or I don't know how?
My code sample is:
SQLiteDatabase db = this.getReadableDatabase();
Cursor daCursor = db.rawQuery(selectQuery,null);
if (daCursor != null) {
if( daCursor.moveToFirst() ){
do{
// String Orchard_ID =
daCursor.getString(daCursor.getColumnIndex("Orchard_Id"));
String Orchard_ID = daCursor.getString(0);
Log.i("dbhandler fetchAllOrchards cursor Orchard_ID",
Orchard_ID);
Log.i("dbhandler fetchAllOrchards cursor Orchard_ID",
Orchard_Name);
} while (daCursor.moveToNext());
} else{
Log.i("cursor is false","fail");
}
}
I am trying to update the database on the basis of incoming parameter but it is not updated.
i am using the following code:
public static void markFavoriteStation(String station, boolean favorite){
Log.d(AppConstants.TAG,"StationListDBIfc: +markFavoriteStation");
String Query = null;
mDb = bartDb.getWritableDatabase();
Query = "update stationlistTable set favorite ='1' where namewithabbr = '+station'";
mDb.rawQuery(Query, null);
Log.d(AppConstants.TAG,"StationListDBIfc: -markFavoriteStation");
}
I think you might have a malformed String definition. You should end the String before concatenating the "station" variable to it, like so:
Query = "update stationlistTable set favorite ='1' where namewithabbr = '" + station + "'";
I can't see any errors. I guess the SQL query has errors or the namewithabbr column doesn't contain what you expect. You should test it in the sqlite3 app.