This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 6 years ago.
I have this app which gets users data from the database using the username they logged in with. The user name is passed once they login to the page which retrieves their account information. The app crashes saying retrieving the information was wrong, can anyone help?
The database code
public Cursor RetriveLoggedUsersData (DatabasOpperations DBOpp, String Username){
SQLiteDatabase SQDB = DBOpp.getReadableDatabase();
String[] Coloumns = {TableData.TableInfo.FIRSTNAME, TableData.TableInfo.LASTNAME, TableData.TableInfo.EMAIL, TableData.TableInfo.USERNAME, TableData.TableInfo.PASSWORD, TableData.TableInfo.IMAGE};
String Where = TableData.TableInfo.USERNAME + " LIKE ?";
String Argument[] = {Username};
Cursor Cur = SQDB.query(TableData.TableInfo.TABLE_NAME, Coloumns, Where, Argument, null, null, null);
Log.d("DatabaseOperations", "Success, User Retrived");
return Cur;
}
The code which wants to retrieve the data
Username = getIntent().getExtras().getString("Username");
DatabasOpperations DB = new DatabasOpperations(Contx);
Cursor Cur = DB.RetriveLoggedUsersData(DB, Username);
DBFName = Cur.getString(0);
DBLName = Cur.getString(1);
DBEmail = Cur.getString(2);
You need to move the Cursor to the first position by making a call to moveToFirst(), and also check the return value to make sure there is at least one row in the Cursor. Also be sure to close your Cursor:
Cursor Cur = DB.RetriveLoggedUsersData(DB, Username);
if (Cur.moveToFirst()) {
DBFName = Cur.getString(0);
DBLName = Cur.getString(1);
DBEmail = Cur.getString(2);
}
Cur.close();
Related
I've got very strange problem.
My snippet is looking like that
public Wynik getData(int pomiar, int godzina) {
Wynik wynik = null;
String query = "SELECT * FROM " + "insulina" + " WHERE godzina = " + godzina +
" AND cukier = " + pomiar;
SQLiteDatabase db = this.getReadableDatabase();
try (Cursor cursor = db.rawQuery(query, null)) {
Log.i("tag", "cursor length:" + cursor.getCount());
if (cursor.getCount() > 0) {
String s = DatabaseUtils.dumpCursorToString(cursor);
Log.d("s", s);
cursor.moveToFirst();
wynik = new Wynik
(cursor.getInt(cursor.getColumnIndexOrThrow("godzina")),
cursor.getString(cursor.getColumnIndexOrThrow("insulina")),
cursor.getInt(cursor.getColumnIndexOrThrow("dawka")),
cursor.getString(cursor.getColumnIndexOrThrow("cialo")));
}
cursor.close();
return wynik;
(sorry for not English convention, but it was meant to be quick, routinely project)
Whole app idea is to help my friend with his grandmother's diabetes. He would insert an result of blood sugar level test (cukier) and time of test is checked automatically (godzina).
Based on those, app should return a whole result (wynik), with required dose of insulin (dawka), type of it (insulina) and part of body from which the blood should be taken (cialo).
Database looks like this:
So for example. The blood result is 10 (it's only thing which user is inserting) and it's 7 P.M (19, by 24-hours convention - the program is giving the closest hour of test, so it's 18). So, the query looks like
SELECT * FROM insulina WHERE godzina = 18 AND cukier = 10
And here's my problem. The app is recognizing cursor length as 0 (it should be 1) even if my other app related to database creation (DB Browser for SQLite) is giving out my result properly with the same query
Also Android Studio says that database is sucessfully opened.
I cannot find a fault here. And I'm really confused with this problem.
I think the query should be :
String query = "SELECT * FROM insulina WHERE godzina = ? AND cukier = ?";
SQLiteDatabase db = this.getReadableDatabase();
try (Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(godzina), String.valueOf(pomiar)})) {
//... rest of code
Also looks like you're using "try with resources" so the close isn't explicitly necessary.
I have made an app, which allows users to add favourites to a SQLite database which in turn loads the information into a favourites arraylist, which is displayed in the favourites activity. When the user clicks 'add to favourites button', this function is executed:
public void loadFavourites() {
SQLiteDatabase db = dbHelper.getReadableDatabase(); //Get the database from which to read values
//Get columns and create a cursor database query
String[] columns = {"favouriteId", "title", "owner", "url_m", "ownerPic", "description", "dateTaken"};
Cursor cursor = db.query("favourites", columns, null, null, null, null, "favouriteId");
Log.d("FavouritesDB", "" + cursor.getCount()); //Displays cursor count in the logcat
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
favID = cursor.getInt(0);
title = cursor.getString(1);
owner = cursor.getString(2);
url_m = cursor.getString(3);
ownerPic = cursor.getString(4);
description = cursor.getString(5);
date = cursor.getString(6);
ImageInfo favourite = new ImageInfo();
favourite.dateTaken = date;
favourite.description = description;
favourite.ownerPic = ownerPic;
favourite.url_m = url_m;
favourite.owner = owner;
favourite.title = title;
NetworkMgr.getInstance(this).favouritesImageList.add(favourite);
cursor.moveToNext(); // Move to next entry
}
}
This successfully adds the image to the favourites arraylist and displays it when the user visits the favourites activity page.
However, every time the app is closed and reopened, the favourites activity is empty, and does not show favourites already added to the database, as the loadFavourites method hasn't been called.
However, if I call the loadFavourites method in the favourites activity onCreate(), every time the page is loaded, the favourites from the database are all added again to the arraylist, so this creates duplicates of each favourite item.
Please could someone suggest how I could fix my loop so that when my app launches, only existing favourite items from the database are added, and are not added again to the arraylist each time the activity is loaded?
Clear favourites arraylist just before calling loadFavourites()
or add favouritesarraylist.clear in the first line of loadFavourites()
When your app launches you need to check if your DB contains items if not add. Adjust below code for your app
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM table";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0){
return;
} else {
//populate table
}
I am creating an application. I need the email of the existing user, which is already saved in the first table, and save it into the second table. Which queries or functions do I need to achieve this? Any suggestions?
First, you need to fetch the user's email by passing on the valid row id:
public Cursor getRecord(long id) throws SQLException {
Cursor cursor = this.database.query(true, databaseTable, new String[] {columnId, columnName, columnEmail}, columnId + "=" + id, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Please note, you may have different columns so change the String[] array with your designated columns. Now, we can create another function to save that email in another table like so:
public long insertExistingUser(String name, String email) {
ContentValues contentValues = new ContentValues();
contentValues.put(columnName, name);
contentValues.put(columnEmail, email);
return this.database.insert(otherDatabaseTable, null, contentValues);
}
This will insert the other user's information into the other table. In order for this to work in your application:
DatabaseAdapter db = new DatabaseAdapter(this);
db.open();
Cursor cursor = db.getRecord(current_user_id);
if (db.insertExistingUser(cursor.getString(1), cursor.getString(2)) > 0)
Toast.makeText(this, "Old user's info was inserted!", Toast.LENGTH_SHORT).show();
db.close();
The cursor.getString(1) requires a number that indicates what column it is. Usually, 0 is the id column which you use to get the user's email.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm having a hard time exactly visualizing 'Cursor' functionality in my program. I kind of get the jist of it, but can anyone explain it's functionality in detail?
By Cursor, I mean the Cursor interface.
I can't simply understand the role it plays with anything.
http://developer.android.com/reference/android/database/Cursor.html
A Cursor object is returned from a query on a SQLite database.
It will return all rows that the query returns.
Say you have a table called names in your database database configured as such:
_id _name
1 Space Ghost
2 Zorak
3 Moltar
4 Brak
If you want to get all data from this table and use it, you would do
something like this:
public HashMap<Integer, String> getNames(){
HashMap<Integer, String> data = new HashMap<Integer, String>();
try{
SQLiteOpenHelper helper = new MyOpenDbHelper(context);
SQLiteDatabase db = helper.getReadableDatabase();
String selectQuery = "SELECT * FROM names";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()){ //make sure you got results, and move to first row
do{
int mID = cursor.getInt(0); //column 0 for the current row
String mName = cursor.getString(1); //column 1 for the current row
data.put(mID, mName);
} while (cursor.moveToNext()); //move to next row in the query result
}
} catch (Exception ex) {
Log.e("MyApp", ex.getMessage());
} finally
{
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
return data;
}
Usually you will create your own class to extend SQLiteOpenHelper, as such:
public class MyOpenDbHelper extends SQLiteOpenHelper {
//........
}
From Wikipedia
In computer science, a database cursor is a control structure that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. The database cursor characteristic of traversal makes cursors akin to the programming language concept of iterator.
From Here
A cursor is a tool that allows you to iterate the records in a set. It has concepts of order and current record.
From The documentation you pointed yourself
provides random read-write access to the result set returned by a database query.
So don' t think Cursor as a functionality, but as a mean for reaching records in a more efficient way from any database.
Are you reffering to this Cursor usage?
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
//Cursor points to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
Hello I develop register screen in android and I need to get id from my database by entered username and password that stores database and make it as int.Firstly user will register then type name and pass and login up.In my database I have many raws like:id username password.I want to get id of entered username and password.For ex:id:1 username:A pass:a id:2, username:B pass:b.. and when user A entered his name and pass and login up i should get his id then make it int type if you dont something please leave comment thanks
I tried to made attempt but i dont know is it rightand how to develop it:
EditText name;
String Username = name.getText().toString();
Cursor c = database.rawQuery("SELECT * FROM " +LOGIN_TABLE + " where username = '"+Username+"'", null);
and in this code Login table is my table name?
If you are using the built in id field of the database, I recommend changing the query a bit.
I find that if I did not define the _id row in my create table statement, I do not get it in Select * statements.
Cursor c = database.rawQuery("SELECT * FROM " +LOGIN_TABLE + " where username = '"+Username+"'", null);
Can be switched to:
Cursor c = database.rawQuery("SELECT _id, * FROM " +LOGIN_TABLE + " where username = '"+Username+"'", null);
After that, when you get it from the cursor, use this to find the id:
Long id = c.getLong(c.getColumnIndex("_id"));
EDIT:
Before calling the last line of code here, make sure to move the cursor to the first result.
if (c.moveToFirst())
{
id = c.getLong(c.getColumnIndex("_id"));
}
Get the id from database as:
String id = c.getString(1);//c is object of cursor
then convert to integer by using Integer.parseInt()
int integerId = Integer.parseInt(id);
public void addData(View view){
DBHandler dbHandler = new DBHandler(this);
//normally the id is comming as int , i changed it to string
long val = dbHandler.addInfo(username.getText().toString(), password.getText().toString());
if(val > 0){
Toast.makeText(this, "Inserted Successfully", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Inserting Error", Toast.LENGTH_LONG).show();
}
}