Android Database help needed - android

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.

Related

Query Database with an array list and get an array list of results back

I have setup an application which currently can lookup an input id with one on the database to then give a single result. E.g. user enters id = 1 , database contains a record with an id of 1 then returns the name or number etc...
Now I want to improve the system slightly by querying my database with an arraylist which contains a range of id's e.g. 3, 456, 731 etc... which I want my database to search for. I have also grouped multiple values to certain id's for example the database might search for an id of 3 it will then find 5 results I want it to return the telephone number of each one of those results into another arraylist which I can print to the logs.
I hope I have explained this enough, but please ask questions if you require more information.
The code below demonstrates the modified version of the query used to gain a single result, but I cannot see what I'm doing wrong to gain multiple results.
Activity....
// New array list which is going to be used to store values from the database
ArrayList<String> contactsList;
// This arrayList has been received from another activity and contains my id's
ArrayList<String> contacts = intent.getStringArrayListExtra("groupCode");
// The database which i'm using
ContactDBHandler contactDBHandler = new ContactDBHandler(getApplicationContext(), null, null, 1);
//getAllValues is used to pass my arraylist id's to the database.
contactsList = contactDBHandler.GetAllValues(contacts);
// Simple log statement to loop and display results
for (int i = 0; i < contactsList.size(); i++){
Log.i("Numbers", contactsList.get(i));
}
ContactDBHandler
Query
// I'm telling it to get the contact number from the contact_list
// when the groupcode matches the code recieved.
public ArrayList<String> GetAllValues(ArrayList groupCode)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
String alarmName = "";
ArrayList<String> list = new ArrayList<>();
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code=?", new String[]{groupCode+ ""});
if (cursor.moveToFirst())
{
do
{
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
return list;
}
Thanks
Can you see where I have gone wrong?
Try this:
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (" + TextUtils.join(",", Collections.nCopies(groupCode.size(), "?")) + ")", groupCode.toArray(new String[groupCode.size()]));
Your current code fails to pass the list in the sql-format: = does only support single values, for lists you have to use IN.
Your code would result in a query like this:
SELECT contact_number FROM contact_list WHERE grp_code=["some_id","other_id"]
But what you need (and my code produces) is:
SELECT contact_number FROM contact_list WHERE grp_code IN ('some_id','other_id')
References:
SQL query to find rows with at least one of the specified values
WHERE IN clause in Android sqlite?
IN clause and placeholders
https://developer.android.com/reference/android/text/TextUtils.html#join(java.lang.CharSequence,%20java.lang.Iterable)
You cannot pass an ArrayList to an SQLQuery. To check for multiple values in the same field you have to use the 'in' keyword.
Ex:
SELECT * FROM `table1` where column in ( 'element1', 'element2', 'element3')
In your case,
String str = "";
for(String s: groupCode){
str = str+","+"\'"+s+"\'";
}
//to remove the extra ' in the begining
str = str.substring(1);
return str;
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (?)", new String[]{str});

How to get SQLite database Column values as List in android

I have three column, first id, second title and third body.
Like this
id title body
1 t1 b1
2 t2 b2
3 t3 b3
So, I want to get title and display in list with listview and if I click t2 title then display body of respective clickable title.
What i did.
DatabaseHelper.java
public Cursor retriveTitle(String [] title) {
Cursor c = null;
c = myDataBase.rawQuery(
"select id,title from book,", title);
return c;
}
Main.java
private void displayTitle() {
try {
myDataBase = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
Cursor cursor = myDataBase.rawQuery("SELECT b.id, b.title FROM book b ", new String[] { "" });
String test=cursor.getString(cursor
.getColumnIndex("title"));
//How to display title of book in listview
}
getting this:
01-18 14:20:03.401: E/AndroidRuntime(6704): Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
I am using already database file, according to this blog post: Using your own SQLite database in Android applications
Try out
Cursor cursor = myDataBase.rawQuery("SELECT b.id, b.title FROM book b",null);
curosr.moveToFirst();
String test=cursor.getString(cursor
.getColumnIndex("title"));
I think your query should use a "where" statement
c = myDataBase.rawQuery("select id,title from book where title=?", title);
Of course you want to pass a certain number of arguments
c = myDataBase.rawQuery("select id,title from book where title in (?, ?, ?)", new String[]{title1, title2, title3});
But then if the number of title can vary, you will need to dynamically create a string with enough question marks. See this post
IN clause and placeholders
If you still get en error, maybe providing more log could help. Also if the lo say what line fails, tell which one it is. we can't see line numbers here
Good luck
Here's how it worked out for me. In an other class, I have created a method of List type and added the column id & the name of the item in the list from the sqlite database.
Here's the piece of code to retrieve the column id of the selected item.
public List<String> list;
adapt = new MyAdapter(this, R.layout.list_inner_view, list); //custom adapter
listTask.setAdapter(adapt);
listTask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
Integer id = list.get(position).getId();
//position is the position of the item in the list.
}
});
Result: the item is at 3rd position in the list. Its database column_id (auto increment) value is 12 because I have deleted previous items. So the result you expect is 12, which is the value of variable id.
If you don't understand this fully, it may be because I haven't posted my entire code. But I'll help you out with your problem.

Android query where clause on ListView

I created a ListView with a CursorAdapter, populated by a table of my db. After I added a ContextMenu that with a long click on the desired line of ListView pick info from my table.
The problem is that: I can not collect the information of that single line of ListView, each line gives me the same result. I think I do something wrong in query.
onCreate:
private void createTabRegistry(SQLiteDatabase db)
{
String sql = "CREATE TABLE {0} ({1} INTEGER PRIMARY KEY AUTOINCREMENT, {2} TEXT,{3} INTEGER,{4} TEXT,{5} TEXT,{6} TEXT, {7} TEXT);";
db.execSQL(MessageFormat.format(sql, TabRegistry.TABLE_NAME, TabRegistry._ID,TabRegistry.TYPE, TabRegistry.DATE, TabRegistry.STATUS, TabRegistry.NUMBER, TabRegistry.MESSAGE, TabRegistry.OTHER));
}
My query in db class:
public Cursor getRegistry2(long id) {
return (getReadableDatabase().query(
TabRegistry.TABLE_NAME,
TabRegistry.COLUMNS,
TabRegistry._ID + " = " + id,
null,
null,
null,
null,
null));
}
id of ContextMenu in my activity:
AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
id = getListAdapter().getItemId(info.position);
My cursor in the activity class:
Cursor c3 = databaseHelper.getRegistry2(id);
if (c3 != null) {
c3.moveToFirst();
}
dbnumber = (c3.getString(c3.getColumnIndex(TabRegistry.NUMBER)));
How do I assign to dbnumber string the value of the line of ListView that wonder?
EDIT code that works, but reset the view of listview....
Cursor c3 = (Cursor) getListAdapter().getItem(info.position);
startManagingCursor(c3);
aaaaa = c3.getString(c3.getColumnIndex(TabRegistry.NUMBER));
c3.close();
AdapterView.AdapterContextMenuInfo has a field called id that represents the row id from the database of that selected row. You'll want to query for that id and not the position field that represents the position in the list:
rowId = info.id;
and then query your database for the rowId to get that item's data.
Edit:
You'll probably don't want to use the solution you added. You close the cursor so no more data(that is why you have to restart the activity, as you probably query the database only in the onCreate method).
I told you the check if info.id returns different values when you use long press(to show the ContextMenu) different rows in the list, that means that the ContextMenu(probably) selects different row ids for different rows).
I don't know what causes your issue(if the delete works I would say there is something in the activity), so I made a small example of what you are trying to do so you can see this type of code:
http://pastebin.com/Yri03S0T

Retrieve the contents of first three rows of a android database using a cursor

Currently in my code i'm using a cursor to retrieve the entire database
My code is
public Cursor getAll() {
return (getReadableDatabase().rawQuery(
"SELECT _id, note, amt, dueDate FROM New", null));
}
The function of retrieving the contents is to populate the same in a listview.
Now I want to retrieve the contents of the first three rows of the same database using cursor to display in another listview.
Need Help, Thanks in Advance.
The correct way to do it is to limit the result number to three:
"SELECT _id, note, amt, dueDate FROM New ORDER BY _id LIMIT 3"
Then you just iterate over the cursor (as usual)
Since you've already obtained a Cursor, in order to get the first three rows of the result, you do this:
Cursor cursor = getAll();
cursor.moveToFirst();
int count = 0;
while(!cursor.isAfterLast() && count < 3)
{
// Grab your data here using cursor.getLong(0), cursor.getString(1) etc.
// and store it an array.
count++;
cursor.moveToNext();
}
cursor.close();
You may want to limit the query results to at most three by adding a LIMIT 0,3 statement to your SQL. Having obtained an array of at most three elements containing your records, you can then proceed to place them in the other ListView you are referring to. You do this by adding them to this ListView's source array. Then call the ListView adapter's notifyDataSetChanged method to have it update itself.
So you can do this in two ways:
Create a separate select:
SELECT * FROM Table_Name LIMIT 3;
Select three rows from cursor:
int n = 0;
cursor.moveToFirst();
while (!cur.isAfterLast() && n < 3) {
// Use the data
n++;
cur.moveToNext();
}
cur.close();

How can I attach a SQLite ID to a Spinner object in android?

I want to pull a couple columns from a database and add those to the spinner, but I want the _id of the row to be hidden in there somewhere too. Take partial sample code below for example:
public void fillProfileSpinner()
{
String query = "SELECT _id,fruit_type,weight,colour FROM fruits;";
SQLiteDatabase profileDatabase = fruitCakes.database.getReadableDatabase();
Cursor cursor = profileDatabase.rawQuery(query, null);
startManagingCursor(cursor);
try {
cursor.moveToFirst();
do
{
String fruitType = cursor.getString(cursor.getColumnIndex("fruit_type"));
double weight = cursor.getString(cursor.getColumnIndex("weight"));
String colour = cursor.getInt(cursor.getColumnIndex("colour"));
fruitAdapter.add(colour + " " + weight + " " + fruit_type);
}
while(cursor.moveToNext());
}
catch(Exception e)
{
e.printStackTrace();
}
cursor.deactivate();
cursor.close();
profileDatabase.close();
}
I believe this is what I'm looking for, however I find it very confusing:
Android Spinners, say I pull spinner selections from SQL, can I also add their SQL _id's to the spinner values?
How can I get the _id column in there somewhere, so that is accessible from some method in the spinner object?
I cannot think of a scenario where your _ID value is not already directly available to you or derivable via the position:
In onListItemClick() of a ListActivity, it is the id parameter
In onItemClick() of a OnItemClickListener, it is the id parameter
Anywhere else that you have a position (e.g., getView() of a ListAdapter), call moveToPosition() on your Cursor and retrieve your _ID that way

Categories

Resources