Autocompeletextview & customtable - android

HI i have a autocompletextview ,when am typing in autocomplete textview i need to directely query the custom table ,insted put it in array, My custom table contain list of names, how can i do this?

You should use SimpleCursorAdapter
SQLiteDatabase db // reference to database
// note that your query result should have an id field with name "_id"
Cursor cursor = db.rawQuery("select name_id as _id, name from table_names", new String[]{});
// create adapter over cursor, returned from database
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_dropdown_item_1line, cursor, new String[]{"name"}, new int[]{android.R.id.text1});
AutoCompleteTextView autocomplete = (AutoCompleteTextView)findViewById(R.id.autocomplete_id);
autocomplete.setAdapter(adapter);
Also you should look at SimpleCursorAdapter.CursorToStringConverter to convert data from cursor to String, which will be displayed. Maybe this link helps you with SimpleCursorAdapter.CursorToStringConverter

Related

Retrieving Particular column from db into Spinner

My SqliteDB
In the above link am having my db screenshot
How to load that fiGoods column values into Spinner. Since am new to android kindly help me with full code
Write Query to get fiGoods
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select fiGoods from fiGoodsDetail", null);
String[] figoodslist;
res.moveToFirst();
int i=0;
while(!res.isAfterLast())
{
figoodslist[i] = res.getString(res.getColumnIndex("fiGoods"));
i++;
}
Get fiGoods value in String array.Then you have to bind array to spinner like this...
ArrayAdapter<String> adaper = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, YOUR_STRING_ARRAY);
spinner.setAdapter(adaper);
To link sqlite values to an adapter, use the handy CursorAdapter class.

Android - populate ListView SQLite, cursor null pointer

I have two tables atm, users and notes. I am trying to retrieve data that belongs to the user. So all data to list must be owned by the original user and shown only to him. I have made my table in Databasehelper.
I have made a new class that controls the notes table. In listNotes() I want to loop through the cursor row and get all data owned by the user. Am I quering it correctly?
// Listing all notes
public Cursor listNotes() {
Cursor c = db.query(help.NOTE_TABLE, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
db.close();
return c;
}
I then want to display the cursor data collected in a listview
public void populateList(){
Cursor cursor = control.listNotes();
getActivity().startManagingCursor(cursor);
//Mapping the fields cursor to text views
String[] fields = new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE};
int [] text = new int[] {R.id.item_title,R.id.item_body, R.id.item_date};
adapter = new SimpleCursorAdapter(getActivity(),R.layout.list_layout,cursor, fields, text,0);
//Calling list object instance
listView = (ListView) getView().findViewById(android.R.id.list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
You aren't creating the NOTE_TABLE right.
You miss a space and a comma here
+ COLUMN_DATE + "DATETIME DEFAULT CURRENT_TIMESTAMP"
It has to be
+ COLUMN_DATE + " DATETIME DEFAULT CURRENT_TIMESTAMP,"
There are two issues here:
One is you have missed a comma (after the Timestamp as specified in an earlier answer).
The other error you have is when using a SimpleCursorAdapter, you need to ensure that the Projection string array includes something to index the rows uniquely and this must be an integer column named as "_id". SQLite already has a feature built in for this and provides a column named "_id" for this purpose (however you can have your own integer column which you can rename to _id). To solve this, change your projection string array to something like:
new String[] {"ROW_ID AS _id", help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}
I guess the NullPointerException stems from this (but without the stacktrace I don't know for sure).

How to show 2 database values in ListView?

I have 2 activities(Novamensagem & Mensagenssalva) in Novamensagem.java I have a spinner with contacts values, a EditText and a Save button. I select a contact and write a text and hit save. The TEXT gets saved, and when i open Mensagenssalva.java all the TEXTs i write and save is there in a ListView. So i want to know how to the ListView show the name of the contact i selected in the Spinner and then show the message. eg:
Person's name
Message i have written.
//EDIT//
now the error is: Force to Close the app when i compile it. The code now:
ListView user = (ListView) findViewById(R.id.lvShowContatos);
//String = simple value ||| String[] = multiple values/columns
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
c = db.query( "contatos", campos, null, null, null, null, null);
c.moveToFirst();
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
list.add(c.getString(c.getColumnIndex("telefone")).toString());
if(!c.moveToNext()) break;
}
}
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.nome_entry, R.id.telefone_entry };
SimpleCursorAdapter myAdap = new SimpleCursorAdapter(this, R.layout.listview, c , campos, to, 0);
user.setAdapter(myAdap);
The LogCat errors:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mensagem/com.example.mensagem.Contato}: java.lang.IllegalArgumentException: column '_id' does not exist
So the thing is, its trying to pull a "_id" from my database, but i dont have a "_id" column/row in it.
Posted from comments
You will have more control over your app while writing less lines of code by using a SimpleCursorAdapter as we discussed.
In order to use any CursorAdapter, your table must have a _id INTEGER PRIMARY KEY column, which you don't have. While I still recommend altering your table to add this column, there is a quick fix. If you don't specify a primary key all SQLite tables create an integer primary key by default, you can reference it with rowid, oid or _rowid_. But Android requires that the integer primary key column is named _id... Simply create an alias with the keyword AS for the meantime:
String[] campos = new String[] {"rowid as _id", "nome", "telefone"};
You need to create customAdapter instead of ArrayAdapter. Check out this link http://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/

How to add an item to SimpleCursorAdapter?

I have a simple database table with 2 columns "_id" and "title".
and I'm displaying the data in a spinner, and it works well.
but I need to add one more item at the top of the spinner list that is not from the database with id = 0 and title = "not specified";
Spinner list = (Spinner) findViewById(R.id.spinner);
Cursor cursor = database.getAll(); // returns cursor with objects
String[] columns = new String[] {"title"};
int[] to = new int[] {R.id.title};
list.setAdapter(new SimpleCursorAdapter(this, R.layout.object_item_simple, cursor, columns, to));
I need to know the selected item id from the database, i can do this with list.getSelectedItemId();
so I can't use ArrayAdapter instead of SimpleCursorAdapter, because i don't think that there is a method for setting the id for each item on the adapter.
is there a way to do this?
Thanks.
You could create an object out of your id and title and build a list of these objects with the cursor. Then insert your artificial entry at the top top of that list.
Then when you construct your Adapter pass in this list.
Alternatively you could put a dummy value into your database, although that would be weird and maybe not possible depending on your query and data. The ArrayAdapter is much more sensible
How to Do This With SimpleCursorAdapter
This method:
Is Efficient
Works with standard CursorLoader and SimpleCursorAdapter idioms
Great with ContentProvider data
I create the item i want to insert into the cursor as a static MatrixCursor
private static final MatrixCursor PLATFORM_HEADER_CURSOR = new MatrixCursor(
//These are the names of the columns in my other cursor
new String[]{
DataContract.ReflashPackage._ID,
DataContract.ReflashPackage.COLUMN_PLATFORM
});
static {
PLATFORM_HEADER_CURSOR.addRow(new String[]{
"0",
"Select a Platform")
});
}
Here is my implementation of onLoadFinished which merges the cursor and passes it to the adapter.
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case PLATFORM_CURSOR_LOADER_ID:
Cursor mergedCursor = addPlatformHeaderToCursor(data);
mPlatformAdapter.swapCursor(mergedCursor);
break;
}
}
#NonNull
private static Cursor addPlatformHeaderToCursor(Cursor platforms) {
Cursor[] cursorToMerge = new Cursor[2];
cursorToMerge[0] = PLATFORM_HEADER_CURSOR;
cursorToMerge[1] = platforms;
return new MergeCursor(cursorToMerge);
}
One technique that I use often is I will define an object (such as EntryObject) that has the variables I am going to need from the cursor to display. Once I have this I can iterate through the cursor and place the information into those EntryObjects and place them in an ArrayList or an array.
Then you can build a customer ArrayAdapter that will work with your new object to pull as much data as you need and display it how you want to.

android sqlite listview cursor problem

From my main.java:
Cursor c = db.getDue();
String[] columns = new String[] { "_id", "date" };
int[] to = new int[] { R.id.num, R.id.date };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.lventer, c, columns, to);
ListView lv1 = (ListView)findViewById(R.id.ListView01);
lv1.setAdapter(mAdapter);
From my database wrapper class:
public Cursor getDue() {
//String getdue = "SELECT * FROM tb1"; // this returns _id+date and displays them in the listview via the cursor adapter, defined above
String getdue = "SELECT _id, max(date) AS date FROM tb1 GROUP BY _id";// this only works if I remove the "date" bindings defined above, only letting me see the _id, i want to see both _id and date in the lit view.
return db.rawQuery(getdue,null);
If I use the second select statment then it crashes unless I remove the "date" from the cursor adapter/listview bindings, if I do this then It will show the returned _id in the listview, but I want to see both _id and date in the listview.
I have been told that the second statment might returns a different type for date because of the max function ( I am not very sql literate, yet), but I thought that sqlite was loose with datatypes? Can anybody help, thanks in advance.
** UPDATE** This is the command that wont work with 2 columns fr the list view:
SELECT _id, max(date) FROM jobs GROUP BY _id HAVING max(date) < (date-21)
Use this:
String getdue = "SELECT _id, max(date) AS date FROM tb1 GROUP BY _id";

Categories

Resources