Get custom itemsAdapter id using cursor android - android

I'm trying to pass the item clicked to another activity i.e from A to B using a custom itemsAdapter with sqlite.
How can I achieve the following?
1)Get the item clicked position using cursor
2)Pass the item clicked to another activity
I'm trying to do similar to this example but use my own custom adapter
I have dome the following so far.
Activity A:
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this,F32Activity.class);
Cursor cursor = (Cursor) itemsAdapter.getItem(position);
intent.putExtra("PROPERTY_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
return;
}
Activity B:
propertyId = getIntent().getIntExtra("PROPERTY_ID", 0);
System.out.println(employeeId);
SQLiteDatabase db = (new Helper(this)).getWritableDatabase();
Cursor cursor = db
.rawQuery("SELECT * from my_table WHERE pro._id = ?",
new String[] { "" + propertyId });
Added the Adapter
private void getItemId(int position) {
// TODO Auto-generated method stub
}
private void getDataAndPopulate() {
// TODO Auto-generated method stub
image = new ArrayList<byte[]>();
bedrooms= new ArrayList<String>();
address= new ArrayList<String>();
propType= new ArrayList<String>();
Cursor cursor = getEvents(" gall,properties where properties._id = gall._id " );
while (cursor.moveToNext()) {
//String temp_id = cursor.getString(0);
byte[] temp_image = cursor.getBlob(2);
String temp_identifier = cursor.getString(1);
String temp_price = cursor.getString(3);
String temp_bedrooms = cursor.getString(4);
String temp_address = cursor.getString(5);
String temp_propType = cursor.getString(6);
image.add(temp_image);
//System.out.println(image);
bedrooms.add(temp_bedrooms);
address.add(temp_address);
propType.add(temp_propType);
}
String[] identifierArray = (String[]) bedrooms.toArray(new String[bedrooms
.size()]);
itemsAdapter = new ItemsAdapter(PropertyResult.this,
cursor, R.layout.activity_f9, identifierArray);
setListAdapter(itemsAdapter);
}
private class ItemsAdapter extends BaseAdapter {
String[] items;
public ItemsAdapter(Context context, Cursor cursor,int textViewResourceId,
String[] items) {
this.items = items;
}
public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
TextView ident;
TextView pric;
TextView bedroom;
TextView addres;
TextView propertytyp;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.activity_f9, null);
}
img = (ImageView) view.findViewById(R.id.image);
bedroom = (TextView) view.findViewById(R.id.bedrooms);
addres = (TextView) view.findViewById(R.id.address);
propertytyp = (TextView) view.findViewById(R.id.propertytype);
bedroom.setText("£"+bedrooms.get(POSITION));
addres.setText(address.get(POSITION));
propertytyp.setText(propType.get(POSITION));
img.setImageBitmap(BitmapFactory.decodeByteArray(
image.get(POSITION), 0, image.get(POSITION).length));
return view;
}
public int getCount() {
return items.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
}
Please kindly give me a solution.

In the onListItemClick() you already have the row id from the cursor, is the 4th parameter, id(this only works for cursor adapters).
First of all also create and ArrayList that will hold long values(the row ids from the cursor):
ids = new ArrayList<Long>();
//...
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);// if 0 is your column containing the id(check it)
ids.add(temp_id);
//...
}
Then in your adapter override the method getItemId and return the long values from the ids ArrayList according to the position supplied:
public long getItemId(int position) {
return ids.get(position);
}
Then in your onListItemClick() simply use the id parameter:
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this,F32Activity.class);
intent.putExtra("PROPERTY_ID", id);
startActivity(intent);
}
Then in the receiving activity:
propertyId = getIntent().getLongExtra("PROPERTY_ID", 0);

Your on Item should like this
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
String strEventName, strEventDate;
int Id;
Cursor c = (Cursor) arg0.getAdapter().getItem(position);
intent.putExtra("PROPERTY_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);}

Related

Get the id from listview when an item is clicked

I have a column in the database _id I would like to get this id when an list view item is clicked. Currently the code below is giving me the position of the item. I' am still playing around with it I have a feeling something is wrong in the method 'getItemId'
onCreate method
ArrayList<String> arrayCatNames = new ArrayList<String>();
String query = "SELECT * FROM category ORDER BY name ASC";
Cursor results = myDB.rawQuery(query, null);
while(results.moveToNext()){
String catName = results.getString(results.getColumnIndex("name"));
arrayCatNames.add(catName);
}
String[] catNamesArr = new String[arrayCatNames.size()];
catNamesArr = arrayCatNames.toArray(catNamesArr);
lvActivityCategory = (ListView) findViewById(R.id.lvActivityCategory);
lvActivityCategory.setAdapter(new categoryCursorAdaptor(this, catNamesArr));
lvActivityCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), categoryActivity.class);
intent.putExtra("category_id", id);
Context context = getApplicationContext();
String s = Long.toString(position);
CharSequence text = s;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
categoryCursorAdaptor
class categoryCursorAdaptor extends BaseAdapter {
Context context;
String[] data;
private static LayoutInflater inflater = null;
public categoryCursorAdaptor(Context context, String[] data) {
this.context = context;
this.data = data;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.length;
}
#Override
public Object getItem(int position) {
return data[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) vi = inflater.inflate(R.layout.item_category, null);
TextView text = (TextView) vi.findViewById(R.id.itemListCategory);
text.setText(data[position]);
return vi;
}
}
ArrayList<String> arrayCatNames = new ArrayList<String>();
ArrayList<Integer> arrayIds = new ArrayList<Integer>();
String query = "SELECT * FROM category ORDER BY name ASC";
Cursor results = myDB.rawQuery(query, null);
while(results.moveToNext()){
String catName = results.getString(results.getColumnIndex("name"));
int Ids = results.getInt(results.getColumnIndex("_id"));
arrayCatNames.add(catName);
arrayIds.add(Ids);
}
Then in your onItemClick
yourCategoryId = arrayIds.get(position);
You need to declare your ArrayList arrayIds at the top, before your onCreate

Trying to get the _id when an item in gridview is clicked getting a cast exception

I am trying to get the _id field from the cursor when an item in my Grid View is clicked, the same code is working fine in a listview but does not seem to work here:
Class level:
CurAdapter Cur;
GridView grid;
onCreate:
Cursor mCur = dbHelper.contactsQuery();
grid = (GridView)rootView.findViewById(R.id.gridview);
Cur = new CurAdapter(getActivity(), mCur,0);
grid.setAdapter(Cur);
grid.setTextFilterEnabled(true);
onCLick:
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
System.out.println(position);
System.out.println(id);
Cursor cursor = (Cursor) grid.getItemAtPosition(position);
}
});
My CustomAdapter:
private class CurAdapter extends CursorAdapter{
public CurAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv = (TextView) view.findViewById(R.id.item_text);
tv.setTypeface(helv_light);
final RoundedImageView iv = (RoundedImageView) view.findViewById(R.id.item_image);
String name = (cursor.getString(cursor.getColumnIndexOrThrow("Name")));
image = cursor.getString(cursor.getColumnIndexOrThrow("imageUri"));
String isAdhoc = (cursor.getString(cursor.getColumnIndexOrThrow("isAdhoc")));
if(isAdhoc.equals("1")){
boolean check = false;
String frName = null;
Cursor mCur = dbHelper.friendsName(name);
if(mCur != null && mCur.moveToFirst()){
do{
frName = mCur.getString(mCur.getColumnIndex("FriendsName"));
if(frName != null){
if(frName.equalsIgnoreCase(selfName)){
check = false;
}else {
check = true;
}
}
}while (mCur.moveToNext());
}
if(check){
name = name+" "+"("+frName+"'s"+" pet)";
}
}
tv.setText(name);
if((image.contains("jpg") || image.contains("png")) && image.contains("adhoc") != true){
image = "file://"+image;
}
final DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.icon_default)
.showImageForEmptyUri(R.drawable.icon_default)
.showImageOnFail(R.drawable.icon_default)
.resetViewBeforeLoading(true)
.cacheInMemory(true) // default
.cacheOnDisk(true) // default
.build();
ImageLoader.getInstance().displayImage(image, iv, options);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.grid_layout, null);
return view;
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return position;
}
}
My Problem:
11-10 14:51:47.989: E/AndroidRuntime(11194): java.lang.ClassCastException: java.lang.Integer cannot be cast to android.database.Cursor
11-10 14:51:47.989: E/AndroidRuntime(11194): at com.example.FragmentTab3$1.onItemClick(FragmentTab3.java:125)
you are getting the ClassCastException because you are overriding getItem
public Object getItem(int position) {
return position;
}
and in your case it is returning an int not the cursor. You can delete it and use the parent implementation of getItem (which should return the Cursor at position)
Exception is due to return int from getItem(..) as mentioned by blackbelt
This may also help you to get ID of the record - change getItemId(..) this way:
public long getItemId(int position) {
mCur.moveToPosition(position);
return mCur.getLong(mCur.getColumnIndex(BaseColumns._ID));
}

Android AdapterView cannot display database records in some device

I would like to ask some question about AdapterView.
In my application, there is an activity which retrieve data from database and display them in AdapterView.
However, when i install the application in different devices, I found that the part I have just mentioned could only function on some devices. The others cannot show the database results.
Here is my code:
private void showResults(String query) {
Cursor cursor = searchCustByInputText(query);
if (cursor == null) {
//
} else {
// Specify the columns we want to display in the result
String[] from = new String[] {
"cust_code",
"chinese_name"};
// Specify the Corresponding layout elements where we want the columns to go
int[] to = new int[] {
R.id.scust_code,
R.id.schinese_name};
// Create a simple cursor adapter for the definitions and apply them to the ListView
SimpleCursorAdapter customers = new SimpleCursorAdapter(this,R.layout.cust_list_item, cursor, from, to);
mListView.setAdapter(customers);
// Define the on-click listener for the list items
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor) mListView.getItemAtPosition(position);
String cust_code = c.getString(c.getColumnIndex("cust_code"));
if (callFromAct.equals("Main")) {
String pay_term = c.getString(c.getColumnIndex("pay_term"));
String chinese_name = c.getString(c.getColumnIndex("chinese_name"));
String english_name = c.getString(c.getColumnIndex("english_name"));
String address_1 = c.getString(c.getColumnIndex("address_1"));
String address_2 = c.getString(c.getColumnIndex("address_2"));
String address_3 = c.getString(c.getColumnIndex("address_3"));
String address_4 = c.getString(c.getColumnIndex("address_4"));
String contact = c.getString(c.getColumnIndex("contact"));
String telephone = c.getString(c.getColumnIndex("telephone"));
String last_order_date = c.getString(c.getColumnIndex("last_order_date"));
//Pass data to another Activity
Intent it = new Intent(CustEnqActivity.this, CustEnqDetailsActivity.class);
Bundle bundle = new Bundle();
bundle.putString("cust_code", cust_code);
bundle.putString("pay_term", pay_term);
bundle.putString("chinese_name", chinese_name);
bundle.putString("english_name", english_name);
bundle.putString("address_1", address_1);
bundle.putString("address_2", address_2);
bundle.putString("address_3", address_3);
bundle.putString("address_4", address_4);
bundle.putString("contact", contact);
bundle.putString("telephone", telephone);
bundle.putString("last_order_date", last_order_date);
it.putExtras(bundle);
startActivity(it);
}
else {
returnToCallingAct(cust_code);
}
//searchView.setQuery("",true);
}
});
}
}
Besides, I discovered there were two warnings in my logcat.
The constructor SimpleCursorAdapter(Context, int, Cursor, String[], int[]) is deprecated
AdapterView is a raw type. References to generic type AdapterView should be parameterized
Are they related to the problem?
Try to create a class that extends BaseAdapter and use ViewHolders for performance
eg:
public class MyBaseAdapter extends BaseAdapter {
ArrayList<ListData> myList = new ArrayList<ListData>();
LayoutInflater inflater;
Context context;
public MyBaseAdapter(Context context, ArrayList<ListData> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context); // only context can also be used
}
#Override
public int getCount() {
return myList.size();
}
#Override
public ListData getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.layout_list_item, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.tvTitle, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.tvDesc, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.ivIcon, myList.get(position).getImgResId());
return convertView;
}
// or you can try better way
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
More info/example:
http://www.pcsalt.com/android/listview-using-baseadapter-android/#sthash.lNGSCiyB.dpbs

retrieve data from sqlite to perform edit/delete by clicking an item in custom listview with 3 fields/columns

sir, can you help me on how i can display the details from a sqlite by clicking its corresponding custom listview item? my listview contains three columns so i wanted it to be displayed in another activity where i can edit the information and delete, etc.. at first, i thought of using row id but gave up on the idea because if i tried to delete an item in database, i cannot use the deleted row id. so the row ids of listview and database won't match. for ex. row ids from database 1,2,3... if i deleted row 2, if i add another item, it will just add to row 4... like this row 1,3,4. thanks for help in advance
public class CustomListView extends Activity {
final Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GroupDb info = new GroupDb(this);
info.open();
ArrayList<Contact> searchResults = info.getView();
final ListView lv = (ListView) findViewById(R.id.srListView);
lv.setAdapter(new MyCustomBaseAdapter(this, searchResults));
info.close();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
here is my custombaseadapter
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<Contact> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<Contact> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
holder.status = (TextView) convertView.findViewById(R.id.status);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtPhone.setText(searchArrayList.get(position).getPhoneNumber());
holder.status.setText(searchArrayList.get(position).getStatus());
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtPhone;
TextView status;
}
}
here is how i saved the database values with three fields/columns from GroupDb.class in my customlistview
public ArrayList<Contact> getView()
{
// TODO Auto-generated method stub
ArrayList<Contact> results = new ArrayList<Contact>();
String[] columns = new String[]{KEY_NAME, KEY_NUMBER, KEY_STATUS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String sName = "";
String nName = "";
String status = "";
int iName = c.getColumnIndex(KEY_NAME);
int iNumber = c.getColumnIndex(KEY_NUMBER);
int iStatus = c.getColumnIndex(KEY_STATUS);
Contact contact;
for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext())
{
contact = new Contact();
sName += c.getString(iName);
nName += c.getString(iNumber);
status += c.getString(iStatus);
contact.setName(sName);
contact.setPhoneNumber(nName);
contact.setStatus(status);
results.add(contact);
sName = "";
nName = "";
status = "";
}
return results;
}
You are maintaining arraylist of contacts. On click of list view get the position fetch contact object from that given position from your arraylist. You must have to save primary key column in your COntact Class.

Android listview with header layout

I am rephrasing my question. Please bear with me.
I have a Cursor, which has carNum and tasks needs to be done on that. So carNum repeats in table. Right now I am using SimpleCursorAdapter and displaying all the info as a listitem. What I would like to do is set carNum as a header of a list and tasks need to be done as listitems. In addition to this, I would like to make header it's own layout so that I can display carNum and some info about it. So now where should I start ?
How should I get distinct carNum from Cursor and make that as header ? And then get listitem for that ?
Here is the .java
public class MyTask extends Activity{
String empid;
ListView list;
Cursor cursor = null;
TextView text;
private DbAdapter_Assignment assignment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listlayout);
empid = getIntent().getExtras().getString("EmpID");
getData(empid);
}
public void getData(final String empid)
{
assignment = new DbAdapter_Assignment(getBaseContext());
assignment.open();
cursor = assignment.getAcceptedTasks(empid);
startManagingCursor(cursor);
text = (TextView) findViewById(R.id.employeename);
text.setText(getEmployeeName(empid) + " has "+ Integer.toString (cursor.getCount()) + " tasks assigned." );
list = (ListView) findViewById(R.id.mytasklist);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View v, int arg2,
long arg3) {
}
});
SimpleCursorAdapter adapter = new SimpleCursorAdapter (this, R.layout.mytaskslayout, cursor, new String[] {"A","B", "C", "D", "E", "F"}, new int[] {R.id.a, R.id.b, R.id.c, R.id.d, R.id.e, R.id.f});
list.setAdapter(adapter);
extend SimpleCursorAdapter
Build list of header indexes in the constructor
c.moveToFirst();
int headerIndex = -1;
String headerValue = null;
do {
headerIndex++;
String header = c.getString(getColumnClass());
if (!header.equalsIgnoreCase(headerValue)) {
mHeaderIndexes.add(headerIndex);
headerValue = header;
headerIndex++;
}
}while (c.moveToNext());
c.moveToFirst();
mDataCount = c.getCount()+mHeaderIndexes.size();
Override methods
#Override
public int getCount() {
return mDataCount;
}
#Override
public int getItemViewType(int position) {
if (mHeaderIndexes.contains(position)) {
return TYPE_HEADER_ROW;
}
return TYPE_ROW;
}
#Override
public Object getItem(int position) {
if (mHeaderIndexes.contains(position)) {
// for header row need return first row with data for this group
getCursor().moveToPosition(position-mHeaderIndexes.indexOf(position));
}
else {
for (int i = 0; i < mHeaderIndexes.size(); i++) {
if (mHeaderIndexes.get(i) > position) {
// need move back by number of headers before position
getCursor().moveToPosition(position - i);
break;
}
}
if (position>mHeaderIndexes.get(mHeaderIndexes.size()-1)) {
// if position is in the last group (position >last group header position)
// move back by number of headers
getCursor().moveToPosition(position - mHeaderIndexes.size());
}
}
return getCursor();
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public boolean isEnabled(int position) {
return !mHeaderIndexes.contains(position);
}
Implement getView()
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
Cursor cursor = (Cursor) getItem(position);
View view = convertView;
if (type==TYPE_HEADER_ROW) {
boolean isHeader = view!=null && view.findViewById(R.id.title)!=null;
if (!isHeader) {
view = mInflater.inflate(R.layout.row_my_header, null);
}
TextView header = view.findViewById(R.id.title);
header.setText(...);
}
else {
if (view==null) {
view = mInflater.inflate(R.layout.row_my_data, null);
}
// fill data row
}
return view;
}

Categories

Resources