How to get an ID from database into the ListView - android

I learn work with Android. I started to create a project with Contacts.
I insert contacts into the SQLite database and then I put them from the database and show them in ListView. Thats OK. But I would like to click on an item in the List and then to edit the item. Therefore I need to get somehow the ID of the item and work with it...I do not know if it is clear...As you can see, in the function onItemClick() , there is running a new activity ...and in the new activity, I need the ID of the item in order to work with it.
public class ContactList extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seznam_kontaktu2);
SQLInsert info = new SQLInsert(this);
info.open();
ArrayList<String> data = info.getDataArrayList(); //It returns Array of "Lastname, Name" which is shown in the List
info.close();
ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter (new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
startActivity(new Intent("net.johnyho.cz.EDITOVATKONTAKT"));
}
});
}

One option that has worked for me is to create a custom ArrayAdapter class along with a custom AdapterItem class. We store the id on our AdapterItem, and return it using our custom ArrayAdapter.
MyAdapterItem might look something like ...
public class MyAdapterItem implements Comparable
{
public String name;
public long rowId;
public MyAdapterItem()
{
rowId = -1L;
name = "";
}
public MyAdapterItem(long _rowId, String _name)
{
rowId = _rowId;
name = _name;
}
public int compareTo( Object o )
{
return toString().compareTo(o.toString());
}
public String toString()
{
return name;
}
}
Our custom ArrayAdapter, MyAdapter, then overrides getItemId(). It reads and returns the stored row id (making the assumption it is working with elements of MyAdapterItem). The other methods on ArrayAdapter will continue to work with our custom class - the toString method is used by the list for display purposes, and by providing a compareTo method the list knows how to sort the values.
public class MyAdapter<MyAdapterItem> extends ArrayAdapter
{
public MyAdapter(Context context, int resourceId)
{
super(context, resourceId);
}
#Override
public long getItemId( int position )
{
MyAdapterItem item = (MyAdapterItem)this.getItem(position);
return item.rowId;
}
}
Back in your Activity's onCreate the OnItemClickListener now provides the correct row id in the "id" parameter.
What is not shown is the new implementation of info.getDataArrayList() - it must be modified to create new MyAdapterItem objects instead of simple Strings.
ArrayList<MyAdapterItem> data = info.getDataArrayList();
ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter( new MyAdapter<MyAdapterItem>(this, android.R.layout.simple_list_item_1, data) );
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
// do whatever - the value in "id" is supplied by getRowId on our adapter
}
});
Also, if you attach a context menu to your ListView, the MenuItem objects passed into your Activity's onContextItemSelected method will also return the correct row id.
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long rowId = info.id;
// do something with the id
}

public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
startActivity(new Intent("net.johnyho.cz.EDITOVATKONTAKT"));
}
hi i dont know what are the column names of your application.but for example id is your primary key identifier then move cursor to arg2 postion and get the value of _id and then pass it to startActivity and it will work.first thing apply SQLiteOpenHelper class its easy for use then apply this.

Related

Getting ID value when clicking on listview

I'm having some trouble getting the correct id value when clicking on the listview.
I made a custom adapter since I'm drawing from SQLite data, I get the right text back but when I click on a row, I get a 0 index id back, which is not what I want.
I'm also using Sugar ORM, so I'm not sure if that requires some special work from me to get the id field.
I'm not sure what I should show you in terms of code, so whatever you think will help you, let me know and I'll post it.
Thanks
BoardArrayAdapter adapter = new BoardArrayAdapter(this, boards);
setListAdapter(adapter);
ListView lv = getListView();
registerForContextMenu(lv);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Board ID " + id, Toast.LENGTH_SHORT).show();
}
});
You need to override the getItemId() method in your adapter.
According to the SugarORM docs you can call getid()to return the db id.
ArrayList<Object> data;
#Override
public long getItemId(int position) {
return data.get(position).getid();
}
This is how I am using on my project (with SQLite and CustomListView).
getData method
public void getData(View view, long id)
{
//storing the ID into a public static variable and converting to int
CLIENTE_ID = (int)id;
//When the user touches on the field in the listview, I get the touched field's name and email
TextView textViewnome = (TextView) view.findViewById(R.id.tv_cliente_nome);
TextView textViewemail = (TextView) view.findViewById(R.id.tv_cliente_email);
//Stores both name and email of the touched field
String nome = textViewnome.getText().toString();
String email = textViewemail.getText().toString();
//store into static variable
CLIENTE_NOME = nome;
CLIENTE_EMAIL = email;
}
within onCreate:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
getData(view, id);
Log.d("myClass", "ID: " + view.getId());
}
});
I hope it helps! :)

How can I get the row id of the a table in the sqlite database when an Item is clicked in the listview

My code goes here.............! when there is a row deleted from the list-view. The indexes of the rows of the listview is changed but the primary key id in the database is not changed. now when i click the item and pass the position of the clicked item of the listview to the new activity. And try to retrieve the record with that ID it does not return me something or incorrect data is returned. now my question is how can I detect the row id of the clicked item of listview in the database.
Now what should be code inside the onItemclick method to retrieve the correct rows from the database.
Thanks in anticiaption......!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DBHelper(this);
titles = myDb.getAllNames();
times = myDb.getAllTimes();
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, titles);
lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
}
});
}
First of all you have to write a query and retrieve id in your database.You must return the id in a cursor.
Refer the below code snippet:
public Cursor fetchAllNames() {
Cursor mCursor = app.myDbHelper.MyDB().query("cardlist", new String[] {"cardid as _id","cardname","carddesc"},
null, null, null, null, null);
try{
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}catch(Exception e)
{
return mCursor;
}
}
Then in your java page:
Cursor cursor = myDB.fetchAllNames();
Then you can get the database id by:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
if(cursor!=null){
System.out.println("position===>"+position);
if(cursor.moveToFirst()){
cursor.moveToPosition(position);
String cardid = cursor.getString(cursor.getColumnIndex("_id"));
}
}
}
});
you will get the database id in the string cardid. You must use _id if you are using SimpleCursorAdapter else you must replace _id with that of the column name that represents your id in the sqlite database.
There's an easy way to achieve so :
First, create an object to represent one line in your database. Since I don't know what your database contains, let's just call it "Title".
public class Title {
private long id;
private String title;
// Constructor, setters and getters
}
Then, create a custom adapter. It will store a collection of Title which will allow you to get it when an item is clicked.
public class TitlesAdapter extends ArrayAdapter<Title> {
private Context context;
private List<Title> items;
public TitlesAdapter(Context context, List<Title> items) {
super(context, R.layout.row_draweritem, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) { /* ... */ }
}
You can then set your adapter in your activity easily:
this.titlesAdapter = new TitlesAdapter(context, titles);
listView.setAdapter(this.titlesAdapter);
... and define your onItemClickListener so you can get back the row id in your database
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
long id = titlesAdapter.getItems().get(i).getId();
}
});
You can learn more about custom adapters in this article : http://www.vogella.com/tutorials/AndroidListView/article.html

How to get correct ID of AutoCompleteTextView adapter

I am new to Android development and I ran into a problem which I find difficult to solve. I am trying to figure out how to use an AutoCompleteTextView widget properly. I want to create a AutoCompleteTextView, using XML data from a web service. I managed to get it to work, but I am defenitely not pleased with the output.
I would like to put a HashMap with id => name pairs into the AutoCompleteTextView and get the id of the clicked item. When I click on the autocomplete filtered set output, I want to populate a list underneath the autocompletion box, which I also managed to get to work.
Done so far:
autocomplete works well for simple ArrayList, all data filtered
correct
onItemClick event fires properly after click
parent.getItemAtPosition(position) returns correct String
representation of the clicked item
The event onItemClick(AdapterView parent, View v, int position, long id) does not behave as I would like. How can I figure out the unfiltered array position of the clicked item? The position of the filtered one is the one I am not interested in.
Further questions:
How to handle HashMaps or Collections in AutoCompleteTextView
How to get the right itemId in the onItemClick event
I did very extensive research on this issue, but did not find any valuable information which would answer my questions.
The event onItemClick(AdapterView parent, View v, int position, long
id) does not behave as I would like.
This is a normal situation when filtering an adapter. Although the adapter keeps a reference to the initial unfiltered data from its point of view it has a single set of data on which is based(no matter if is the initial one or resulted from a filter operation). But this shouldn't raise any problems. With the default sdk adapters(or with a subclass), in the onItemClick() you get the position for the current list on which the adapter is based. You could then use getItem() to get data item for that position(again it doesn't matter if initial or filtered).
String data = getItem(position);
int realPosition = list.indexOf(data); // if you want to know the unfiltered position
this will work for lists and Maps(assuming that you use the SimpleAdapter). And for a Maps you always have the option of adding an additional key to set the unfiltered position in the initial list.
If you use your own adapter along with an AutoCompleteTextView you could make the onItemClick() give you the right id(the position however you can't change).
public class SpecialAutoComplete extends AutoCompleteTextView {
public SpecialAutoComplete(Context context) {
super(context);
}
#Override
public void onFilterComplete(int count) {
// this will be called when the adapter finished the filter
// operation and it notifies the AutoCompleteTextView
long[] realIds = new long[count]; // this will hold the real ids from our maps
for (int i = 0; i < count; i++) {
final HashMap<String, String> item = (HashMap<String, String>) getAdapter()
.getItem(i);
realIds[i] = Long.valueOf(item.get("id")); // get the ids from the filtered items
}
// update the adapter with the real ids so it has the proper data
((SimpleAdapterExtension) getAdapter()).setRealIds(realIds);
super.onFilterComplete(count);
}
}
and the adapter:
public class SimpleAdapterExtension extends SimpleAdapter {
private List<? extends Map<String, String>> mData;
private long[] mCurrentIds;
public SimpleAdapterExtension(Context context,
List<? extends Map<String, String>> data, int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
mData = data;
}
#Override
public long getItemId(int position) {
// this will be used to get the id provided to the onItemClick callback
return mCurrentIds[position];
}
#Override
public boolean hasStableIds() {
return true;
}
public void setRealIds(long[] realIds) {
mCurrentIds = realIds;
}
}
If you also implement the Filter class for the adapter then you could get the ids from there without the need to override the AutoCompleTextView class.
Using the Luksprog approach, I made some similar with ArrayAdapter.
public class SimpleAutoCompleteAdapter extends ArrayAdapter<String>{
private String[] mData;
private int[] mCurrentIds;
public SimpleAutoCompleteAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
mData=objects;
}
#Override
public long getItemId(int position) {
String data = getItem(position);
int index = Arrays.asList(mData).indexOf(data);
/*
* Atention , if your list has more that one same String , you have to improve here
*/
// this will be used to get the id provided to the onItemClick callback
if (index>0)
return (long)mCurrentIds[index];
else return 0;
}
#Override
public boolean hasStableIds() {
return true;
}
public void setRealIds(int[] realIds) {
mCurrentIds = realIds;
}
}
Implement onItemClickListener for AutoCompleteTextView, then use indexOf on your list to find the index of selected item.
actvCity.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int index = cityNames.indexOf(actvCity.getText().toString());
// Do Whatever you want to do ;)
}
});
First add your data into custom arraylist
// mList used for adding custom data into your model
private List<OutletListSRModel> mList = new ArrayList<>();
// listdata used for adding string data for auto completing.
ArrayList<String> listdata = new ArrayList<String>();
for (int i = 0; i < JArray.length(); i++) {
JSONObject responseJson = JArray.getJSONObject(i);
OutletListSRModel mModel = new OutletListSRModel();
mModel.setId(responseJson.getString("id"));
mModel.name(responseJson.getString("outlet_name"));
listdata.add(responseJson.getString("outlet_name"));
}
ArrayAdapter adapter = new
ArrayAdapter(getActivity(),
android.R.layout.simple_list_item_1, listdata);
searchOutletKey.setAdapter(adapter);
Now for getting any value from model which we added above. we can get like this.
searchOutletKey.setOnItemClickListener ( new AdapterView.OnItemClickListener ( ) {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String txtOutletId = mOutletListSRModel.get(position).getId();
}
});

How to get spinner string value on android?

I have created a spinner and the items of spinner comes from database. However, When I use
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
typeOFBCard = contactSpinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
When I call this listener and try to pick the chosen string of the spinner i get a reference of the sglite something like:
android.database.sqlite.SQLiteCursor#40535568
This is the return value of typeOfBCard.
However, on the spinner I can see normal string like "Work".
Here is how I initialized the spinner :
contactSpinner = (Spinner) findViewById(R.id.contactSpinner);
mobileText =(EditText) findViewById(R.id.mobileText);
mDbHelper = new DbAdapter(this);
mDbHelper.open();
cursor = mDbHelper.fetchAllBusinessCards();
startManagingCursor(cursor);
context =this;
contactSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
How ever on the spinner I can see normal string like "Work"
That is because you configured an Adapter on the Spinner, and the Adapter is pulling data out of the Cursor to display.
How to get spinner string value on android?
There is no "spinner string value". Spinners don't have strings. They have views. Those views might be instances of TextView, or they might be instances of ImageView, or they might be instances of a LinearLayout holding onto a TextView and an ImageView, or...
If you want to get data out of the Cursor, call getString() on the Cursor.
Every row in a spinner is a view but it's also a value/object from your source.
Try
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// Parent == where the click happened.
typeOFBCard = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}

Edit List Items in ListView

I have a listview from an SQLDatabase using custom CursorAdaptor. I would like to go back to the activity that i used to create the items when i click on them in the listview.so that i can edit the entries. But nothing happen when i implement the OnItemClick method and the getItemId() on the CursorAdapter even though am not sure i am correct there. Here is my Code:
public void onItemClick(AdapterView<?> adapview, View view, int position, long rowId) {
Cursor c = adapter.retrieveRow(rowId); // retrieve row from Database
Intent edit = new Intent(this,NewItem.class);
edit.putExtra(DBAdapter.KEY_ID, rowId);
edit.putExtra(DBAdapter.Title, c.getString(c.getColumnIndex(DBAdapter.Title)));
edit.putExtra(DBAdapter.DATE, c.getString(c.getColumnIndex(DBAdapter.DATE)));
startActivity(edit);
}
public long getItemId(int id){
return id;
}
I think you need to set an onItemClickListener on the Listview rather than trying to implement it in the Adapter class.
EXAMPLE:
mListView = (ListView)findViewbyId(R.id.whatever)
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long rowId) {
Cursor c = adapter.retrieveRow(rowId); // retrieve row from Database
Intent edit = new Intent(this,NewItem.class);
edit.putExtra(DBAdapter.KEY_ID, rowId);
edit.putExtra(DBAdapter.Title, c.getString(c.getColumnIndex(DBAdapter.Title)));
edit.putExtra(DBAdapter.DATE, c.getString(c.getColumnIndex(DBAdapter.DATE)));
startActivity(edit);
}
});
Is this what you're doing?

Categories

Resources