i have a list with data from my database.
I want to have a button in every list item that onClick will delete this item from the database.
Here is how i get the data from the db and present them in a list:
DB entry=new DB(this);
entry.open();
Cursor cursor = entry.getData();
startManagingCursor(cursor);
ListView list=(ListView)findViewById(R.id.list);
String[] columns = new String[] { DBHelper.NAME, DBHelper.SURNAME};
int[] to = new int[] { R.id.textView01,R.id.textView02};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, columns, to);
list.setAdapter(mAdapter);
entry.close();
So,my problem is : How to create a clickable button in every list item
EDIT:
this is the adapter i created:
public class myAdapter extends BaseAdapter {
private Context mContext;
final Drawable delete_btn;
private ImageButton imageButton;
private LayoutInflater inflater;
private List<ITEMS> items = new ArrayList<ITEMS>();
public myAdapter(Context ctx) {
mContext = ctx;
inflater = LayoutInflater.from(mContext);
delete_btn = ctx.getResources()
.getDrawable(R.drawable.delete_btn);
}
public View getView(final int position, View convertView, ViewGroup parent) {
View btv = null;
try {
btv = inflater.inflate(R.layout.row, null);
TextView name = (TextView) btv.findViewById(R.id.textView01);
name.setText(DBHelper.NAME);
TextView surname = (TextView) btv.findViewById(R.id.textView02);
surname.setText(DBHelper.SURNAME);
imageButton = (ImageButton) btv.findViewById(R.id.delete_btn);
imageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Button pressed", Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
return btv;
}
public void addItem(ITEM it) {
items.add(it);
}
public void setListItems(List<ITEM> lit) {
items = lit;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
}
create your own CustomCursorAdapter instead of SimpleCursorAdapter. Here is an example
Related
I have one listview and adapter ImageButton for delete data, but I don't know how to delete data by setOnClick. I need to click ImageButton and delete data. I have data type room not null.
public class OrgManageRoom extends AppCompatActivity {
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> list_of_rooms = new ArrayList<>();
ArrayList<HashMap<String, String>> MyArrList;
public ArrayList<String> arr;
public ArrayAdapter adapter;
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().getRoot();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_org_manage_room);
// listView = (ListView)findViewById(R.id.listView);
// listView.setAdapter(new ImageAdapter(this));
// arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list_of_rooms);
// listView.setAdapter(arrayAdapter);
createAdapter();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(OrgManageRoom.this,OrgAddUser.class);
startActivity(i);
}
});
}
private void createAdapter() {
listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(new ImageAdapter(this));
mDatabase = FirebaseDatabase.getInstance().getReference().child("AllRoom");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()){
set.add(((DataSnapshot)i.next()).getKey());
}
list_of_rooms.clear();
list_of_rooms.addAll(set);
// arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context c) {
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return list_of_rooms.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.deleteroom, null);
}
// ColImgID
TextView txtPosition = (TextView) convertView.findViewById(R.id.ColImgDesc);
txtPosition.setPadding(10, 0, 0, 0);
txtPosition.setText(list_of_rooms.get(position));
ImageButton cmdShared = (ImageButton) convertView.findViewById(R.id.imgCmdShared);
cmdShared.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(OrgManageRoom.this, "test" + list_of_rooms.get(position), Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
}
Sorry, I edit all code and I make project chat firebase and show listview listroom for add user and delete user and manageroom. It deletes room edit nameroom. Same I need to click imagebutton for delete listroom.
Good day
i am having problem when I am trying to delete my item from my sqlite.
it doesn't update my listview.
MAIN ACTIVITY
this is my main activity, both onCreate and onResume
private CustomAdapter customAdapter;
#Override
protected voidonCreate(Bundle savedInstanceState) {
lv = (ListView)findViewById(R.id.memo_list_view);
customAdapter = new CustomAdapter(this, memoIDS, memoTitles, memoCreatedDates, memoAlarmedDates);
}
#Override
protected voidonResume() {
memoIDS.clear();
memoTitles.clear();
memoCreatedDates.clear();
memoAlarmedDates.clear();
Cursor c=SplashActivity.db.rawQuery("SELECT * FROM memos", null);
if(c.getCount()!=0) {
while(c.moveToNext()) {
memoIDS.add(c.getString(0));
memoTitles.add(c.getString(1));
memoCreatedDates.add(c.getString(3));
memoAlarmedDates.add(c.getString(4));
}
c.close();
lv.setAdapter(customAdapter);
}
}
CustomAdapter
from this customadater, i am trying to delete the record i created.
public class CustomAdapter extends BaseAdapter{
List<String> mMemoIds;
List<String> mMemoTitle;
List<String> mMemoCreatedDate;
List<String> mMemoAlarmedDate;
Context context;
private static LayoutInflater inflater=null;
public CustomAdapter(MemoListActivity mainActivity, List<String> memoIds, List<String> memoTitle, List<String> memoCreatedDate, List<String> memoAlarmedDate) {
mMemoIds = memoIds;
mMemoTitle = memoTitle;
mMemoCreatedDate = memoCreatedDate;
mMemoAlarmedDate = memoAlarmedDate;
context = mainActivity;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mMemoIds.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tViewMemoTitle;
TextView tViewMemoCreatedDate;
TextView tViewMemoAlarmedDate;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tViewMemoTitle=(TextView) rowView.findViewById(R.id.memo_list_title);
holder.tViewMemoCreatedDate=(TextView) rowView.findViewById(R.id.memo_list_created_date);
holder.tViewMemoAlarmedDate=(TextView) rowView.findViewById(R.id.memo_list_alarmed_date);
holder.tViewMemoTitle.setText(mMemoTitle.get(position));
holder.tViewMemoCreatedDate.setText("Created Date : " + mMemoCreatedDate.get(position));
holder.tViewMemoAlarmedDate.setText("Alarm Date : " + mMemoAlarmedDate.get(position));
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Cursor c=SplashActivity.db.rawQuery("SELECT * FROM memos WHERE id='"+mMemoIds.get(position)+"'", null);
if(c.moveToFirst())
{
SplashActivity.db.execSQL("DELETE FROM memos WHERE id='"+mMemoIds.get(position)+"'");
notifyDataSetChanged();
}
}
});
return rowView;
}
}
my problem is, i don't know where to put
notifydatasetchanged();
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Cursor c=SplashActivity.db.rawQuery("SELECT * FROM memos WHERE id='"+mMemoIds.get(position)+"'", null);
if(c.moveToFirst())
{
SplashActivity.db.execSQL("DELETE FROM memos WHERE id='"+mMemoIds.get(position)+"'");
mMemoIds.remove(c.getString(0));
mMemoTitle.remove(c.getString(1));
mMemoCreatedDate.remove(c.getString(3));
mMemoAlarmedDate.remove(c.getString(4));
notifyDataSetChanged(); // Insert your notifydatasetchanged here
}
}
});
This is my adapter class :
public class CheckboxAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
Context context;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
ArrayList<String> selectedStrings = new ArrayList<String>();
public CheckboxAdapter(Context ctx, int viewResourceId, String[] strings) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mViewResourceId = viewResourceId;
}
public int getCount() {
return mStrings.length;
}
public String getItem(int position) {
return mStrings[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
final CheckBox tv = (CheckBox) convertView.findViewById(R.id.checkBox1);
tv.setText(mStrings[position]);
tv.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
selectedStrings.add(tv.getText().toString());
Toast.makeText(buttonView.getContext(),Boolean.toString(selectedStrings.add(tv.getText().toString())), Toast.LENGTH_SHORT).show();
} else {
selectedStrings.remove(tv.getText().toString());
}
}
});
return convertView;
}
}
This is my actvity
public class AddTime extends Activity {
CheckboxAdapter cadpter;
String daya[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday",
"Friday", "Saturday" };
ListView list;
ArrayList<String> selectedStrings = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtime);
list = (ListView) findViewById(R.id.listView1);
cadpter = new CheckboxAdapter(AddTime.this, R.layout.list_item, daya);
list.setAdapter(cadpter);
}
}
I am displaying all day in listview also i have display check box with each day when i enable check box it show true in toast but i want what ever i select day using check box i mean i want display all the day in textview in mainactvity please suggest me how i will get it .
how to get all checked value on button click from list-view in android
As adding all checked values in selectedStrings ArrayList. create a method in CheckboxAdapter class which return ArrayList of all selected values. for example :
public ArrayList<String> getAllSelectedValues(){
return this.selectedStrings;
}
Now use cadpter CheckboxAdapter class object for accessing getAllSelectedValuesmethod in Activity:
ArrayList<String> selectedStrings=cadpter.getAllSelectedValues();
get all values from selectedStrings arrayList
for(int i=0;i<=selectedStrings.sizes();i++){
String s =selectedStrings.get(i);
}
Take boolean Array
ArrayList<Boolean> selectedStrings = new ArrayList<>();
and add onClickListener in your checkbox
public View getView(final int position, View convertView, ViewGroup parent) {
-
-
tv.setChecked(false);
if(selectedStrings.size() <= position){
selectedStrings.add(position, false);
}else
tv.setChecked(selectedStrings.get(position));
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean state = selectedStrings.get(position);
selectedStrings.remove(position);
selectedStrings.add(position, state ? false : true);
}
});
}
I had tried to to put checkbox in listview through layout inflator and I got success but the problem is when I select the multiple contacts there is no problem but when I deselect it & when I scroll down & then go back to that deselected checkbox its get automatically selected...
public class Contactlist_selfActivity extends ListActivity {
/** Called when the activity is first created. */
private ArrayList<contact> contact_list = null;
private ProgressDialog mProgressDialog = null;
private contactAdapter mContactAdapter = null;
private Runnable mViewcontacts = null;
private SparseBooleanArray mSelectedContacts = new SparseBooleanArray();
private ArrayList<contact> items;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
contact_list = new ArrayList<contact>();
this.mContactAdapter = new contactAdapter(this, R.layout.listview,
contact_list);
ListView lv = getListView();
setListAdapter(this.mContactAdapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// }
mViewcontacts = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
getContacts();
}
};
Thread thread = new Thread(null, mViewcontacts, "ContactReadBackground");
thread.start();
mProgressDialog = ProgressDialog.show(Contactlist_selfActivity.this,
"Please Wait...", "Retriving Contacts...", true);
}
#SuppressWarnings("unused")
private void getContacts() {
// TODO Auto-generated method stub
try {
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts._ID };
Cursor mCursor = managedQuery(
ContactsContract.Contacts.CONTENT_URI, projection,
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=?",
new String[] { "1" },
ContactsContract.Contacts.DISPLAY_NAME);
while (mCursor.moveToNext()) {
contact contact = new contact();
String contactId = mCursor.getString(mCursor
.getColumnIndex(ContactsContract.Contacts._ID));
contact.setContactName(mCursor.getString(mCursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contact_list.add(contact);
}
mCursor.close();
runOnUiThread(returnRes);
} catch (Exception e) {
// TODO: handle exception
Log.d("getContacts", e.getMessage());
}
}
public class contactAdapter extends ArrayAdapter<contact> {
private int[] isChecked;
public contactAdapter(Context context, int textViewResourceId,
ArrayList<contact> items1) {
super(context, textViewResourceId, items1);
items = items1;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
final int position_clicked = 0;
// Log.i("asd", "getView :" + getItem(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.listview, parent, false);
}
contact contacts = items.get(position);
isChecked = new int[items.size()];
if (contacts != null) {
final CheckBox nameCheckBox = (CheckBox) convertView
.findViewById(R.id.checkBox);
nameCheckBox.setChecked(mSelectedContacts.get(position));
for (int i = 0; i < isChecked.length; i++) {
}
if (nameCheckBox != null) {
nameCheckBox.setText(contacts.getContactName());
}
nameCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isChecked[position_clicked] = position;
Log.d("position", String.valueOf(position));
}
});
}
return convertView;
}
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
mContactAdapter.notifyDataSetChanged();
}
};
}
i found the answer....
i had just taken a new variable in contact class...
public class PlanetsActivity extends Activity {
private ListView mainListView;
private Contact[] contact_read;
private Cursor mCursor;
private ArrayAdapter<Contact> listAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find the ListView resource.
mainListView = (ListView) findViewById(R.id.mainListView);
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
Contact planet = listAdapter.getItem(position);
planet.toggleChecked();
ContactViewHolder viewHolder = (ContactViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
// Throw Query and fetch the contacts.
String[] projection = new String[] { Contacts.HAS_PHONE_NUMBER,
Contacts._ID, Contacts.DISPLAY_NAME };
mCursor = managedQuery(Contacts.CONTENT_URI, projection,
Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
Contacts.DISPLAY_NAME);
if (mCursor != null) {
mCursor.moveToFirst();
contact_read = new Contact[mCursor.getCount()];
// Add Contacts to the Array
int j = 0;
do {
contact_read[j] = new Contact(mCursor.getString(mCursor
.getColumnIndex(Contacts.DISPLAY_NAME)));
j++;
} while (mCursor.moveToNext());
} else {
System.out.println("Cursor is NULL");
}
// Add Contact Class to the Arraylist
ArrayList<Contact> planetList = new ArrayList<Contact>();
planetList.addAll(Arrays.asList(contact_read));
// Set our custom array adapter as the ListView's adapter.
listAdapter = new ContactArrayAdapter(this, planetList);
mainListView.setAdapter(listAdapter);
}
/** Holds Contact data. */
#SuppressWarnings("unused")
private static class Contact {
private String name = "";
private boolean checked = false;
public Contact() {
}
public Contact(String name) {
this.name = name;
}
public Contact(String name, boolean checked) {
this.name = name;
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name;
}
public void toggleChecked() {
checked = !checked;
}
}
/** Holds child views for one row. */
#SuppressWarnings("unused")
private static class ContactViewHolder {
private CheckBox checkBox;
private TextView textView;
public ContactViewHolder() {
}
public ContactViewHolder(TextView textView, CheckBox checkBox) {
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
}
/** Custom adapter for displaying an array of Contact objects. */
private static class ContactArrayAdapter extends ArrayAdapter<Contact> {
private LayoutInflater inflater;
public ContactArrayAdapter(Context context, List<Contact> planetList) {
super(context, R.layout.simplerow, R.id.rowTextView, planetList);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Contact to display
Contact planet = (Contact) this.getItem(position);
System.out.println(String.valueOf(position));
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.rowTextView);
checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new ContactViewHolder(textView, checkBox));
// If CheckBox is toggled, update the Contact it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Contact contact = (Contact) cb.getTag();
contact.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
ContactViewHolder viewHolder = (ContactViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Contact it is displaying, so that we
// can
// access the Contact in onClick() when the CheckBox is toggled.
checkBox.setTag(planet);
// Display Contact data
checkBox.setChecked(planet.isChecked());
textView.setText(planet.getName());
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return contact_read;
}
}
The cause of this is that when you call nameCheckBox.setChecked() in code OnClickListener() awakes and run its code. I had the same problem an solved in just setting OnClickListener(null) before set a checkbox checked or not.
nameCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isChecked[position_clicked] = position;
Log.d("position", String.valueOf(position));
}
});
this code in add more one arre list in stores all position and add or remove both said
fast add ,second remove.
and used to list in position your other method
My ListView consist an ImageView and a TextView I need to get the Text from the TextView.
int the position of my list where I press (onItemClick).
How can I do that?
The 1 class have a Button then when you press I moving to the next activity (CountryView)
and expect to get back from the next activity with a text (name of the selected Country)
The 2 classes have a ListView (ImageView and TextView) the data is getting from a database and showing on the ListView.
My problem is to get back to the 1 class the selected name of the country.
Thanks so much for helping!!!
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// final int recquestCode = 0;
final Button btnCountry = (Button) findViewById(R.id.fromButton);
btnCountry.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent pingIntent = new Intent("CountryView");
pingIntent.putExtra("btnText", " ");
pingIntent.setClass(Travel.this, CountryView.class);
startActivityForResult(pingIntent, RECEIVE_MESSAGE);
}
});
/* Button btnSearch = (Button) findViewById(R.id.searchButton);
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(), ResultView.class);
startActivityForResult(intent, 0);
}
});*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (data.hasExtra("response")){
Button b = (Button)findViewById(R.id.fromButton);
CharSequence seq = data.getCharSequenceExtra("response");
b.setText(seq);
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.country);
mListUsers = getCountry();
lvUsers = (ListView) findViewById(R.id.countrylistView);
lvUsers.setAdapter(new ListAdapter(this, R.id.countrylistView, mListUsers));
// lvUsers.setTextFilterEnabled(true);
// String extraMsg1 = getIntent().getExtras().getString("extra1");
lvUsers.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
//textItem=view;
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Intent pongIntent = new Intent();
// lvUsers.getItemAtPosition(position);
t = (TextView) view;
Log.v("fffvd"+t, null);
t.setText(getIntent().getStringExtra("btnText"));
String strText = t.getText().toString();
//((TextView) view).getText().toString()
pongIntent.putExtra("response",strText);
setResult(Activity.RESULT_OK,pongIntent);
finish();
// startActivity(new Intent(CountryView.this,TravelPharmacy.class));
}
});
}
public ArrayList<Country> getCountry(){
DBHelper dbAdapter=DBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM Pays;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<Country> countryList = new ArrayList<Country>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
Country country = new Country();
try {
//country.id = Integer.parseInt(list.get(0));
country.pays = list.get(1);
// country.age = Long.parseLong(list.get(2));
} catch (Exception e) {
Log.i("***" + TravelPharmacy.class.toString(), e.getMessage());
}
countryList.add(country);
}
return countryList;
}
#Override
public void onDestroy()
{
// adapter.imageLoader.stopThread();
lv.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// adapter.imageLoader.clearCache();
((BaseAdapter) adapter).notifyDataSetChanged();
}
};
CountryAdapter Class
public class CountryAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public CountryAdapter(Activity a, String[] d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder
{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.singlecountry, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+data[position]);
holder.image.setTag(data[position]);
return vi;
}
}
ListAdapter Class
private class ListAdapter extends ArrayAdapter<Country> { // --CloneChangeRequired
private ArrayList<Country> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<Country> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.singlecountry, null); // --CloneChangeRequired(list_item)
}
final Country listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting singleCountry views
// ( (TextView) view.findViewById(R.id.tv_id) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.text) ).setText( listItem.getPays() );
//((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable.world);
//( (TextView) view.findViewById(R.id.tv_age) ).setText( listItem.getAge()+"" );
}}catch(Exception e){
Log.i(CountryView.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
When you add things to the list, you can add hashmaps to the arraylist which the adapter looks at. Then you can grab the values which are name value pairs.
I think you want to get the position of the list you clicked, Its simple you can use OnItemClickListener as follows
YourList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position=arg2;
// where position is the clicked position
} }
If you stored your data in String array pass this position say array[position] to string array you can get the Text..