Im making a login and register system and if need to check if the user already exits so I wrote this function in my database handler to check it.
public boolean checkIfUserExits(String username){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE username=" + "\"" + username + "\"";
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
But the problem if that i always getting a true.
Thanks for help.
Well, it does exist:
From the other function you posted (it can be accessed in the revision history, so double check before posting stuff, as it will stay around even if you edit it away).
user = new User(username, password, email);
dbHandler.createUser(user);
if(dbHandler.checkIfUserExits(username) == true){
You can just remove the == true, that's redundant. Anyway, you create the user, then you check whether it exists. Of course it does, you just created it.
The easy but wrong fix would be to check first, then create the user. Unfortunately, if for some reason two programs do this at the same time, it is very possible they both see the user doesn't exist, and both proceed.
What you probably want to do here would be to try creating the user no matter what, then check whether it worked or not. I dont't know this environment, but for sure you should be able to detect integrity constraint violations.
It's posible that your cursor is null and can't count members... My app uses a similar method but it's more complet and can control errors more good.
Why I pass the complet query? It's simple it's a general method, for a general class. With this you can use this method for all calls and don't need to create a new methods for differents calls... If you need this one for one query, then includes inside how your question.
You can see the code below:
public boolean exists_the_ColumnParameter(String query){
//Declaration of variables
Cursor a3 = null;
try{
a3 = database.rawQuery(query,null);
a3.moveToFirst();
if(a3.getString(0).equals("")){
a3.close();
return false;
}
else{
a3.close();
return true;
}
}
catch (CursorIndexOutOfBoundsException ex){
return false;
} catch (Exception ex){
Log.e("-- BDD.exists_the_ColumnParameter --","Exception",ex);
return false;
}
}
Tell me if I helped you and good programming!
Related
I'm trying to do some Sqlite querying but I don't know if I'm doing it correctly because this feels really unsave to do. So my question is how do I fix this. I'm new to the whole Xamarin and Sqlite usage.
I'm only making a Android project so it is not a cross platform application. I also cant seem to figure out where to get Mono.Data.Sqlite if I even need it. Everything is welcome.
static public List<Users> SelectUser(string name)
{
try
{
var dbConn = new SQLiteConnection(DatabasePath);
{
return dbConn.Query<Users>("SELECT name, email FROM TblUsers where name = " + name+ ";");
}
}
catch (SQLiteException ex)
{
return null;
}
}
You should use Prepared Statements.
There is an official java documentation about Prepared Statements from Oracle here.
You can also search it on google. There are a lot of guides on how to use prepared statements.
i'm searching for hours now, to get a solution for this problem:
at the very beginning of my android app, a layout with buttons is shown to the user. if he clicks on the button "Tasks" a listView should pop up (another activity and layout) to show him all available Tasks, and with a click on one he can do even more things, but they're not necessary for my problem. the point is, the app won't get any Data out of the Database, but when I Step Into or Step Over the lines which call a method for all the DBStuff it works.
Here are the necesssary lines:
if (connection1.OpenDatabase(1, getDataBaseName()))
{
CTask = connection1.DBQueryTable(getDataBaseName(), "Tasks", TempFieldT);
CEquipment = connection1.DBQueryTable(getDataBaseName(), "Equipment", TempFieldE);
connection1.CloseDatabase();
}
so he will run over those lines, execute the lines beneath, but wont give any Data back, when i'm not supervising it with breakpoints, and the steps. when i do it, all things work the way they should.
The Database Stuff the app runs through at this place.
public Android.Database.ICursor DBQueryTable(string DataBaseName, string TableName, string[] Fields)
{
FindDBPath(DataBaseName);
Android.Database.ICursor c;
string TempF = "";
string str = "";
foreach (string n in Fields)
{ TempF += n + ","; }
SQLQuery = "SELECT " + (str = TempF.TrimEnd(',')) +" FROM " + TableName;
c = sqldTemp.RawQuery(SQLQuery, null);
return c;
}
so why do the app/compiler/debugger behave like this? are there any mistakes i did, but i can't figure out right now?
Ps: yeah i know there is a query function, but thats not necessary here as long as it would provide a solution to my problem.
Your DBQueryTable method returns a cursor. That will become invalidated as soon as you close the connection in the following line:
connection1.CloseDatabase();
You should keep the connection open for as long as you need the cursor. For example, you could fetch all the data from the cursor and then close the connection.
I'm attempting to update a calendar's event on my phone from my code, but context.getContentResolver().update keeps returning 0, and of course there are no changes made to the event when I look at it in the Calendar app.
I'm getting the event ID, start time, etc with context.getContentResolver().query, and I'm getting unique numbers like 431, 4, 233, etc, so I'm presuming the event IDs I'm using are real.
I understand the official way to do this is to go through Google's servers instead of using update(), but for my implementation it doesn't make sense to do it that way (or even in general, but I digress).
Am I doing something wrong, or am I trying to do something that Android simply isn't going to allow?
Uri updateEventUri = ContentUris.withAppendedId(Uri.parse("content://com.android.calendar/events"), id);
ContentValues cv = new ContentValues();
begin.set(Calendar.HOUR_OF_DAY, arg0.getCurrentHour()); //begin is a java.util.Calendar object
begin.set(Calendar.MINUTE, arg0.getCurrentMinute());
//cv.put("_id", id);
//cv.put("title", "yeahyeahyeah!");
cv.put("dtstart", begin.getTimeInMillis());
int updatedrowcount = context.getContentResolver().update(updateEventUri, cv, null, null);
System.out.println("updated "+updatedrowcount+" rows with id "+id);
A related question was posted here with no replies https://stackoverflow.com/questions/5636350/update-android-calendar-event
Let me know if I can clarify anything; I would really appreciate any input you guys and dolls could provide!
i had tried a lot and finally ended up with solution (Unreliable though).. but works fine..
public static boolean updateCalendar(Context context,String cal_Id,String eventId)
{
try{
Uri CALENDAR_URI = Uri.parse(CAL_URI+"events");
Cursor c = context.getContentResolver().query(CALENDAR_URI, null, null, null, null);
String[] s = c.getColumnNames();
if (c.moveToFirst())
{
while (c.moveToNext())
{
String _id = c.getString(c.getColumnIndex("_id"));
String CalId = c.getString(c.getColumnIndex("calendar_id"));
if ((_id==null) && (CalId == null))
{
return false;
}
else
{
if (_id.equals(eventId) && CalId.equals(cal_Id))
{
Uri uri = ContentUris.withAppendedId(CALENDAR_URI, Integer.parseInt(_id));
context.getContentResolver().update(uri, null, null, null);// need to give your data here
return true;
}
}
}
}
}
finally
{
return true;
}
}
and finally i'm not sure if it works with every device.
Ok, so, the problem was that I was using different URIs between fetching the events and editing them. I used the code sample from here and was using the URI "content://com.android.calendar/instances/when" to fetch the events and display them on the screen. When I had made a change I was using "content://com.android.calendar/events" to edit by id as in my example above.
What I found, thanks to your response, ntc, was that the ids for events between the two URIs were different, and therefore I couldn't edit the events consistently with the information each was giving me. I was presuming the event ids I was getting were system ids and universal to the phone.
I guess I'll have to do some testing and see what hardware isn't compatible with this method. I am using an HTC Evo for testing and so far so good.
When querying the Instances table, use Instances.EVENT_ID to get the identifier for the event you want to edit, instead of Instances._ID.
I have one problem with my application.
I create a one AsyncTask for downloading list of files from server . When all the files are download after that i update the database. But when i called the update query its give me the below error.
Failure 21 (out of memory) on 0x0 when
preparing update
Can any one tell me why this error occurs ?
Sample Code
public void setStatus(int index)
{
try
{
db.OpenDatabase();
db.updateStatus(id.get(index), 1);
db.closeDatabase();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Above function called from the AsyncTask ....
public void updateStatus(int id,int status)
{
try
{
db.execSQL("update sample set status =" + status + " where id = " + id);
}
catch(Exception e){e.printStackTrace();}
}
This may not be related to the database pe se, but rather to the fact that the memory (heap) is almost full and opening the database completely fills it up.
Remember that most handsets have 48MB of heap or even less.
Sometime while working I also got the same error.
I used this link
"Failure 21 (out of memory)" when performing some SQLite operations
It said that this error occurs when you try to work on a closed DB.
I looked back into my code and found that I was also doing the same. Got it working afterwards
I think you are also trying to work on a closed DB.
Have you tried to use the update() method instead of execSQL()?
public void updateStatus(int id,int status)
{
try
{
ContentValues values = new ContentValues();
values.put("status", status);
db.update ("sample", values, "id = ?", new String[]{Integer.toString(id)});
}
catch(Exception e){e.printStackTrace();}
}
I has "out of memory" error (21) when I try to call sqlite3_prepare() with a NULL pointer to database handle.
Check if your handle is valid and the database is opened.
I am working on a fuel use application which will run on Android 1.6 onwards. The bundled SQLite on v1.6 doesn't do foreign keys, so I've had to handle it manually. So far, I have done this using an Android transaction:
public static long addFuelUp(String registrationNumber, String date)
{
SQLiteDatabase db = uKMpgData.getReadableDatabase();
long result = -1;
ContentValues values = new ContentValues();
Cursor vehicleCursor = VehicleDataProvider.getVehicle(registrationNumber);
if(vehicleCursor.moveToNext())
{
Cursor fuelUpsCursor = getFuelUps(registrationNumber, date);
if(!fuelUpsCursor.moveToNext())
{
db.beginTransaction();
try
{
values.put(REGISTRATION_NO_COLUMN, registrationNumber.replace(" ", ""));
values.put(DATE_TIME_COLUMN, date);
result = db.insertOrThrow(FUEL_USE_TABLE_NAME, null, values);
db.setTransactionSuccessful();
}
catch(SQLException e)
{
Log.d("addFuelUp", e.getMessage());
}
finally
{
db.endTransaction();
vehicleCursor.close();
fuelUpsCursor.close();
}
}
}
return result;
}
I.e. fuel data cannot be entered unless there is a matching vehicle registration number in the database.
My question is, is there a better way to do this? I'm not a database expert, but I know you can set up triggers to enforce rules - are triggers more suited to handle constraints?
Cheers,
Barry
Triggers would be a good solution to this problem.
In fact there is an automated way to generate triggers for simulating foreign keys. SQLite for PC provides a utility called "genfkey" which can examine an existing database which uses foreign keys and outputs the corresponding triggers.