Android spinner/sqlite database - getting cursor position not contents! - android

So my setup is that I have a database with two tables. My main input class is a basic form which has a spinner to select a category. Category is the second table, the spinner is powered by this database table and the main table has a foreign key of this table.
I have the spinner populating correctly etc but when storing the selected item from the spinner it is storing the cursor position which looks like:
android.database.sqlite.SQLiteCursor#435b9ba0.
rather than the actual contents of it which should be the name from the database. The code I am using is:
String fkstring = mSpinner.getSelectedItem().toString();
If anyone could let me know how to solve this that would be great.

use .getString(0) to get a string, .getString(0) will get the first column .getString(1) the second etc etc.
String fkstring = mSpinner.getSelectedItem().getString(0);

Try String fkstring = (String) mSpinner.getSelectedItem();

Related

How to insert a name automatically in the SQLite database when we type that name in the edit box?

My actual meaning is that I want to make an app in which there will be a textboxin the UI and some names will be stored in the database and if I type the name's first word which is in the database that name should appear automatically like the autocomplete view but when we type a new name which is not in the database in the search box then it should add that new name automatically in the database
So what you are trying to do is (1) populate the SQLite database with names as the user enters them - but (2) you always want to retrieve names that are in the database and use these as suggestions for autocomplete.
for (1) here is a good and complete tutorial on SQLite in Android - this should cover what you need to do (including updating/deleting). More specifically, you want to store what the user is entering in the Textbox - so something like this:
....
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//supposing you declared the edit-text as (edtName) properly before...
String nameValue = edtName.getText().toString();
contentValues.put("name", name);
db.insert("<tablename>", null, contentValues);
For (2) - Autocomplete - I suggest you look at this AutoComplete example as well as the AutoCompleteTextView reference. Since you want to retrieve suggestions from SQLite, you should first retrieve the list names from the database and then instantiate your adapter - example (adapt to your use case):
//supposing you have a helper method "getNames" which executes select * query
//and returning list of all names...
String[] namesFromDB = yourDBHelper.getNames();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, namesFromDB);
AutoCompleteTextView textView = (AutoCompleteTextView)findViewById(R.id.names_list);
textView.setAdapter(adapter);
I hope this gets you started.

Android Expandable Listview have header and child from different table

In one of my app i have database table like
Table 1 :Menu
column
ID,
MenuName,
MeuID
and Table 2 Menuproduct
column
menuId,
menuprice
I need it like
i header of expandble list
menu name
and in child price. like that
how to make it possible? as i have to pass MenuId to get menu price
Please help
Thanks
You need to use join query to get the detail from sqlite database
If you want the details based on MenuID then your query will be like following
SELECT Menu.MenuID, Menu.MenuName, menuprice
FROM Menu
LEFT OUTER JOIN Menuproduct ON Menu.MenuID = Menuproduct.menuId;
http://www.tutorialspoint.com/sqlite/sqlite_using_joins.htm
you need to store the result as custom object in array list.Checkout following
exapandible listview

Imported sqlite database is missing data and mixing columns

I have put an sqlite database in my assets folder and imported it onto the phone.
I created an object with multiple properties and when I create a list of that object and assign each property a value from a column of the table they get mixed up
Below is my code
public ArrayList<Exercise> getExercisesFromQuery(String Query) {
ArrayList<Exercise> ExerciseList = new ArrayList<Exercise>();
Cursor cursor = mDb.rawQuery(Query, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Exercise e = new Exercise();
e.setID(Integer.parseInt(cursor.getString(0)));
e.setName(cursor.getString(1));
e.setMuscle(cursor.getString(2));
e.setDescription(cursor.getString(3));
e.setFilepath(cursor.getString(4));
e.setSets(cursor.getString(5));
e.setReps(cursor.getString(6));
e.setEquipment(cursor.getString(7));
e.setPrimaryMuscle(cursor.getString(8));
e.setSecondaryMuscle(cursor.getString(9));
e.setDifficulty(cursor.getString(10));
// Adding contact to list
ExerciseList.add(e);
} while (cursor.moveToNext());
}
return ExerciseList;
}
The current problem is when I do object.getName it gives me the muscle and if I do object.getmuscle it is blank and there is no value but if I do object.getDescription it works fine.
It is not a problem with the database it works fine in any sqlite manager.
Any ideas as to what is wrong?
The reason why the columns are not being returned in the order you expect is not clear. They should come back in the order specified in your query or in the order they are on the table if you are doing SELECT *. However it is not really necessary to address that specific puzzle.
A more defensive and maintainable coding approach is to request each column's index from the cursor by using the getColumnIndexOrThrow method instead of hardcoding them. For example:
int ID_INDEX = cursor.getColumnIndexOrThrow("_id");
int NAME_INDEX = cursor.getColumnIndexOrThrow("name");
If the column doesn't exist you'll get an exception. If it does, you now have its index within the cursor which you can use in the calls to cursor.getString:
e.setID(Integer.parseInt(cursor.getString(ID_INDEX)));
e.setName(cursor.getString(NAME_INDEX));
So you no longer need to worry about what order the columns come back in and you won't need to change any hardcoded index values if your query changes in the future.
Make sure that the columns in the database are in the correct order - column Name should be the second column, column Muscle should be the third column.

android _Displaying a record from a sqlite database

I am planning to build an app that lets the user select a record from a particular database such as:
name favorite_color favorite_team
sue red Dal
mike blue Mia
sam purple Bal
My problem is that most of the tutorials that I have come across only demonstrates examples using a table with one column. What if my pre-populated database more then on column? What if it had 100 columns? Does anyone know how this is done?????
Here's an example:
Step1:Declare SQLiteDatabase,Declare Databasehelper
Step2:Declare string or number which is to be used as key or get it as an intent(in this example 'rowid'
Step 3: In the OnCreate method add lines of code similar to following:
String query="select * from my_table_name where _id="+rowid;
Cursor myCursor = database.rawQuery(query,null);
myCursor.moveToFirst();
//This line implies i am getting data from column four of selected row
String x=myCursor.getString(4);
//This line implies i am getting data from column two of selected row
String y=myCursor.getString(4);
myCursor.close();
Note:
a)Don't forget that your database size must not exceed 1.2mb
b)Also include a column with name _id which auto-increments in each table that you are using,you may use sqlite browser to do so
c)also create the following table in your database :
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
Now insert a single row with the text 'en_US' in the "android_metadata" table
INSERT INTO "android_metadata" VALUES ('en_US')
read this you will learn every thing you need to know. One other way to access db information is using an ORM like ormlite. I'm using it in various apps that i've developed, and it's simple to use.

How to delete row from sqlite at listview Android

I have a listview and i am getting the data from sqlite database. My problem is to delete a row which user selected it from listview. I can delete all table by
dbConn.delete("Restobj", null,null);
But i cant delete a single row which is selected from listview.
Please Help
You essentially need to get the row id from the selected ListView item. Using the row id you can easily delete that row:
String where = "_id = " + _id;
db.delete(TABLE_NAME, where, null);
After deleting the row item make sure you get the ListView adapter cursor and do a requery. If you don't you will not see the updated table, hence updated ListView.
Make use of those other two parameters to the delete method. Take a look at the API documentation for more information.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete%28java.lang.String,%20java.lang.String,%20java.lang.String[]%29
Pass in something other than null.
Also, try searching on stackoverflow and/or Google for this topic. The answers are plentiful.
You need to supply the appropriate values to the database object. I'm assuming that dbConn is an instance of a database object. If that is the case, you can pass in dbConn.delete() with 3 arguments. The first argument is the table name. The second is the whereClause. This is something similar to:
"id = " + objectDatabaseId
The final variable in this case you can leave blank. The end result is something like:
String whereClause = "id = " + objectDatabaseId;
dbConn.delete("Restobj", whereClause, null);
As a side note, it's better to use constants when referring to table names and table columns as apposed to "Restobj" you should have something like RestObject.TABLE_NAME where the constant is defined as a static final String inside of the RestObject.
-Randall

Categories

Resources