SQLite Query data retrieve from cursor - android

I have 2 edit boxes in my UI. I want to retrieve data from a table and I want to insert those retrieved data into those edit text boxes how can I insert data into those edit text boxes from cursor?

check your no. of column and its name cursor.getColumnCount() and cursor.getColumnName(0). respectively.if your column count is 2 then cursor have two column
cursor.moveToFirst();
String columnName1 = cursor.getColumnName(0);
String columnName2 = cursor.getColumnName(1);
String str1 = cursor.getString(cursor.getColumnIndex(columnName1)));
String str2 = cursor.getString(cursor.getColumnIndex(columnName2)));
editext1.seText(str1);
editext2.seText(str2);
after completion of getting data from database close your cursor using cursor.close();

// Activity.onCreate function
EditText etfirstname= (EditText)findViewById(R.id.firstname);
EditText etlastname= (EditText)findViewById(R.id.lastname);
MyDatabase database = new MyDatabase(this);
Cursor c = database.queryRaw("SELECT firstname, lastname FROM users WHERE id=1"); // query data from database
if(c.moveToFirst()){
etfirstname.setText(c.getString(0)); // read firstname
etlastname.setText(c.getString(1)); // read lastname
}
c.close(); // dont forget to close cursor!

Related

SQLiteDatabase delete(table_name, null, null) is not deleting all rows in the table

This is my code :
Db.getInstance().beginTransaction();
int i = Db.getInstance().delete("friends", null, null);
Log.e(TAG, "dropDB: " + i);
Db.getInstance().setTransactionSuccessful();
Db.getInstance().endTransaction();
I have searched the SO community, but cannot find what is wrong in this code. When I delete , the value of i is number of rows deleted, but still the database keeps returning rows.
Db is my own helper class in which I initialise the SQLiteDatabase's object and get getWritableDatabase().
May be nothing, but try only calling getInstance() once and setting it to a variable.
I use this in a CustomDialog when the user clicks the btnYES to delete the table.
I know the table only ever has one record because it hold a password so try this
db = helper.getReadableDatabase();
String q = "SELECT * FROM masterPW";
Cursor cursor = db.rawQuery(q,null);
// Above query gets TABLE_PW data from Col_IDI
// TABLE_PW will only ever have one row of data
int rowID = 99;
if(cursor.moveToFirst()){
rowID = cursor.getInt(cursor.getColumnIndex(Col_IDI));
str = cursor.getString(cursor.getColumnIndex(Col_MPW));
}
cursor.close();
// Line of code below WORKS deletes entire TABLE <=====
// Not a recommended way to re-set the master password
// db.delete(TABLE_PW, null, null);

SQLite extracting day from date issue

I have a DATE field in my database with format 'YYYY-MM-DD'. Now I want to extract only 'day' from that day i.e. 'DD'. My table name is 'date' and the column name where date is stored is 'lastDonated'. How do i do it... please look these codes for more details.
public String day() {
String b = "";
SQLiteDatabase db = getWritableDatabase();
String query = "???(what to place in here?)";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
b = c.getString(c.getColumnIndex("lastDonated"));
c.moveToNext();
return b;
}
I only have one row in the database
Use this query
SELECT strftime('%d', YourDateColumn) AS SomeAlias FROM YourTable
And get the value like this
b = c.getString(c.getColumnIndex("SomeAlias"));
Reference: https://www.sqlite.org/lang_datefunc.html

Cursor returning 0

I have a function where I want to get the sum of values on a MySQL database table's row. This is my code:
public int getSum(int var) {
int x=0;
// Select All Query
String selectQuery = "SELECT sum(amount) FROM donations WHERE aid = '"+aid+"'";
SQLiteDatabase db = openOrCreateDatabase("shareity", Context.MODE_PRIVATE, null);
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
x = cursor.getInt(0);
} while (cursor.moveToNext());
}
// return contact list
Log.d("id", "Id" + "," + x);
return x;
}
And I'm calling this in the onCreate() like this:
getSum(idk);
where idk is an integer. But my this returns 0. Can I know why please? The table's row I want to get the sum of, is also integer.
Finally figured it out. The problem was with the SQLite database. I had to use a php file to download the database from the mysql server to the local Sqlite server and then loop through it

Printing selected database values

I'm currently writing an app which allows you to pick a category, and the app will retrieve all results in that category and print them onto the screen. The code for the creation of the database is fine, but I am unsure on whether my retrieval method is correct, and then totally unsure as to how I would print out the individual names of the results into a TextView.
Currently, I have:
public Cursor getDatabase(int category)
{
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Cursor cur;
cur=myData.rawQuery("select * from youthcentres where cat1='"+category+"' OR cat2 ='"+category+"' OR cat3='"+category+"'",null);
cur.moveToFirst();
myData.close();
return cur;
};
You now need to retrieve the data from the cursor using the appropriate getter methods.
For example, say you retrieved the following from the database:
1. Name (text) 2. Age (integer)
So, when you want to retrieve them from the cursor, you will go as follows:
String name = cur.getString(0);
int age = cur.getInt(1);
Remember that the zero-index is relative to the search query and not the table.
You may have columns in the table as (name,address,class,age) in which case age is at index 3. That doesn't matter to the cursor here :)

Android Database help needed

I have an activity which has two edit text fields: one for the title and the other for the story.
The entries made two text fields are saved in the database, also the database has a ROW_ID,TITLE_ID and STORY_ID. The entries are displayed in a list view.
When an item is long clicked, I get the row id corresponding to that item.
How should I get the TITLE_ID and STORY_ID from this?
Say, you have the corresponing row id of item which is long clicked in a variable rid. Then run the following query:
String q = "SELECT * FROM TABLE_NAME where(ROW_ID like '"+rid+"')";
Cursor c = db.rawQuery(q, null); // db is a object of SQLiteDatabase type
Then retrieve TITLE_ID and STORY_ID like:
if(c.getCount() == 0)
{
//No entry found
}
else {
c.moveToFirst();
do {
String titleid = c.getString(c.getColumnIndex("TITLE_ID"));
String storyid = c.getString(c.getColumnIndex("STORY_ID"));
} while (c.moveToNext());
c.close();
Then use them as you like :)
You could query the data base for the TITLE_ID and STORY_ID that correspond to the ROW_ID.
Post what code you have and we will be able to give more specific answers.

Categories

Resources