Dynamic show the Delete Button in listview on select option - android

I have designed an list view which has one imageview, textview, and button. initially the imageview and textview will be visible on clicking the imageview delete button will visible for selected view but my problem is while selecting the next list option i need to hide the button i need to show only one button at a time. can anyone help me please?
public class HistoryMenu extends MainActivity {
public final static String ITEM_TITLE = "title";
public final static String ITEM_CAPTION = "caption";
public static Boolean deletedispflag=false;
public static View selectdelete=null;
String optionSelectedValue;
ArrayList<String> listString;
ArrayAdapter<String> aa;
ListView settingsSubList;
LayoutInflater linf;
// public String[] stringList={"N # 17.3 MPH (16-18)","10:25, 20 June 2013","N # 17.3 MPH (16-18)","10:25, 20 June 2013","N # 17.3 MPH (16-18)","10:25, 20 June 2013","N # 17.3 MPH (16-18)","10:25, 20 June 2013"};
// HistoryListAdapters historyListAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_menu);
settingsSubList = (ListView) findViewById(R.id.settings_sub_list);
LayoutParams layout = new LayoutParams(Gravity.CENTER);
LayoutInflater inflator = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.centered_menu_title, null);
((TextView)v.findViewById(R.id.title)).setTextColor(getResources().getColor(R.color.white));
this.getSupportActionBar().setCustomView(v,layout);
listString=new ArrayList<String>();
listString.add("history object 1");
listString.add("history object 2");
listString.add("history object 3");
listString.add("history object 4");
listString.add("history object 5");
MyArrayAdapter adapter = new MyArrayAdapter(this, R.layout.history_option_selector, listString);
settingsSubList.setAdapter(adapter);
settingsSubList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int position,
long arg3) {
}
});
}
public class MyArrayAdapter extends ArrayAdapter<String> {
int previousDegrees = 0;
int degrees = 90;
RotateAnimation animation = new RotateAnimation(0f, 90f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); //, 200, 200); // canvas.getWidth() / 2, canvas.getHeight() / 2);
Context context;
int layoutResourceId;
ArrayList<String> historyitems = new ArrayList<String>();
public MyArrayAdapter(Context context, int layoutResourceId,ArrayList<String> historyitems)
{
super(context, layoutResourceId, historyitems);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.historyitems = historyitems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
animation.setDuration(1000L);
View item = convertView;
if (item == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
item = inflater.inflate(layoutResourceId, parent, false);
}
TextView items = (TextView) item.findViewById(R.id.history_list_option_text);
final ImageView select_option = (ImageView) item.findViewById(R.id.history_list_option_select_image);
final Button delete = (Button) item.findViewById(R.id.history_list_option_delete_button);
delete.setVisibility(View.INVISIBLE);
String itemtext = historyitems.get(position);
items.setText(itemtext);
select_option.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
select_option.startAnimation(animation);
if(deletedispflag == false)
{
delete.setVisibility(v.VISIBLE);
selectdelete = v;
deletedispflag=true;
}
else if(deletedispflag==true)
{
delete.setVisibility(selectdelete.INVISIBLE);
deletedispflag=false;
}
Toast.makeText(context, "Edit", Toast.LENGTH_LONG).show();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Delete", Toast.LENGTH_LONG).show();
}
});
return item;
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
overridePendingTransition(R.drawable.activity_in_left_to_right_animation,R.drawable.activity_out_right_to_left_animation);
}
}

You can achieve this by storing the reference previously clicked button
private Button prevDelete;
And change click listener to something like below:
select_option.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(prevDelete!=null){
prevDelete.setVisibility(View.INVISIBLE);
}
delete.setVisibility(View.VISIBLE);
prevDelete = delete;
select_option.startAnimation(animation);
selectdelete = v;
Toast.makeText(context, "Edit", Toast.LENGTH_LONG).show();
}
});

Related

Adding item to listview through a dialog

I'm using a custom listview which I want to add an item to my listview. But it seems to be skipping all the code to add the item. Can someone please tell me how I should adjust my code to achieve this.
Thank you in advance.
This is my Main Activity in which I call a custom Dialog
public class MainActivity extends ActionBarActivity {
TextView threadId;
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newMessage = (Button) findViewById(R.id.new_message_button);
final Context context = this;
final ListView listView = (ListView) this.findViewById(R.id.messagingListView);
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), this.MessageFeedData());
listView.setAdapter(itemAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
listView.getAdapter().getItem(position);
MessageItem itemAtPos = (MessageItem) parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, ConversationView.class);
intent.putExtra("threadId", String.valueOf(itemAtPos.ThreadId));
startActivity(intent);
}
});
newMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.write_message_layout);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
final Button post_button = (Button) dialog.findViewById(R.id.button_post);
final EditText new_write_message = (EditText) dialog.findViewById(R.id.messge_msg);
final EditText to_message = (EditText) dialog.findViewById(R.id.to_newmsg);
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.add(new MessageItem(5458, to_message.getText().toString(), "imh", DateTime.now(), new_write_message.getText().toString()));
itemAdapter.notifyDataSetChanged();
if (v.getId() == R.id.button_post);
to_message.setText("");
new_write_message.setText("");
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_LONG)
.show();
}
});
dialog.show();
}
});
}
public ArrayList<MessageItem> MessageFeedData() {
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
//recieved_item_click_actions fields
items.add(new MessageItem(1, "Bob Doe", "image", DateTime.now(), "Hello how are you?"));
items.add(new MessageItem(200, "Simon Pink", "image", DateTime.now(), "Hello what are you doing"));
return items;
}
class ActivityFeedTask extends AsyncTask<Integer, Void, Void> {
ArrayList<MessageItem> recentTracks;
#Override
protected Void doInBackground(Integer... page) {
try {
recentTracks = new ArrayList<MessageItem>();
Thread.sleep(3000);
MessageItem data = null;
for (int i = 0; i < 10; i++) {
recentTracks.add(data);
}
} catch (Exception e) {
}
return null;
}
}
public class ActivityAdapter extends ArrayAdapter<MessageItem> {
private final Context context;
private final ArrayList<MessageItem> items;
//private int currentPage = 0;
public ActivityAdapter(Context context, ArrayList<MessageItem> recentTrackArrayList) {
super(context, 0, recentTrackArrayList);
this.context = context;
this.items = recentTrackArrayList;
}
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = getLayoutInflater().inflate
(R.layout.message_list_item, parent, false);
rowView = convertView;
TextView comment2 = (TextView) rowView
.findViewById(R.id.messaging_username);
comment2.setText(items.get(position).Username);
ImageView comment3 = (ImageView) rowView
.findViewById(R.id.messaging_photo);
if (items.get(position).Image == null) {
comment3.setImageResource(R.drawable.ic_launcher);
}
TextView comment4 = (TextView) rowView
.findViewById(R.id.messaging_date);
comment4.setText(items.get(position).DateTimeStamp.toString());
TextView comment5 = (TextView) rowView
.findViewById(R.id.messaging_string);
comment5.setText(items.get(position).MessageString);
}
return convertView;
}
}
}
This is my custom Dialog
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/to_newmsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TO" />
<EditText
android:id="#+id/messge_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/to_newmsg"
android:text="MESSAGE" />
<Button
android:id="#+id/button_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/messge_msg"
android:text="Send" />
</RelativeLayout>
You have this
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
before onCreate
while this
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
in MessageFeedData() is local.
Use a single list and add items to the same then call notifyDateSetChanged() to refresh listview.
As you can see you do not use items as an arg to constructor
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), this.MessageFeedData());
Edit:
final ListView listView = (ListView) this.findViewById(R.id.messagingListView);
items = this.MessageFeedData());
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), items);

Deleting the checked items in the listview

I want to make an app which includes a listView with check boxes and a two buttons named add and delete selected. I want to delete all the item that are checked in the list view.I am unable to do that despite of my lot of efforts. Any help would be appreciated.
Here is my code
package com.example.chkbokinlistview;
public class Adapter extends ArrayAdapter<Movies> {
ArrayList<Movies> data;
Context context;
int id;
private Holder h;
public Adapter(Context context, int textViewResourceId, ArrayList<Movies> objects) {
super(context, textViewResourceId, objects);
this.data = objects;
this.context = context;
this.id = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int p = position;
View v = convertView;
LayoutInflater l = ((Activity)context).getLayoutInflater();
h = new Holder();
if (v == null) {
v = l.inflate(id, parent, false);
h.tv = (TextView) v.findViewById(R.id.textView1);
h.cb = (CheckBox) v.findViewById(R.id.checkBox1);
v.setTag(h);
}else{
h = (Holder) v.getTag();
h.cb.setChecked(true);
}
h.tv.setText(data.get(position).movieName);
h.cb.setChecked(data.get(position).deleted);
return v;
}
public void delete(){
//how to delete all the items that are checked
}
class Holder{
TextView tv;
CheckBox cb;
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
bDelete = (Button) findViewById(R.id.bDelete);
bAdd = (Button) findViewById(R.id.bAdd);
list = new ArrayList<Movies>();
a = new Adapter(this, R.layout.listitem, list);
lv.setAdapter(a);
bDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
a.delete();
}
});
bAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final EditText et = new EditText(MainActivity.this);
dialog = new AlertDialog.Builder(MainActivity.this)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
list.add(new Movies(et.getText().toString(), false));
a.notifyDataSetChanged();
dialog.dismiss();
}
})
.setTitle("ADD Movie")
.setView(et)
.create();
dialog.show();
}
});
}
On checking the checkbox add that position in an ArrayList let say toBeDeleted, and when you click delete button, just remove items from your ArrayList named data according to the positions that you have in toBeDeleted and call the adapter method notifyDataSetChanged().
Add a checkedChangedListener in the getView method for your CheckBox.
h.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
// TODO Auto-generated method stub
if (arg1) {
list.add(position);
} else {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == position) {
list.remove(i);
break;
}
}
}
}
});
Where list is a ArrayList<Integer>,
and for deleting
private void delete() {
for(int i = 0 i<list.size;i++)
data.remove(list.get(i));
}
but before deleting you have to sort the list in decending order, in order to remove correctly, otherwise you may get an IndexOutofBoundException

Listactivity With Multiple buttons NullPointerException with scrolling list in landscape mode only

I have a listactivity app , consist of 5 rows , each row contain one TEXT and 5 BUTTON , both text and buttons are clickable , text will open MyDay activity whic is textview and when you click any button it must open videoview screen .
every things run nicely except when turn mobile to landscape mode and scrolling the list it force closed and gave NullPointerException in logcat report in this line
(51) of MyArrayAdapter Class .
logcat:
java.lang.NullPointerException
at com.test.demo.MyArrayAdapter.getView(MyArrayAdapter.java:51)
Line (51) in MyArrayAdapter Class is :
holder.textView.setText(s);
any advice will be appreciated to solve that , thanks .
MyArrayAdapter Class:
public class MyArrayAdapter extends ArrayAdapter<String> {
private final String[] mClasses;
private Context mContext;
private Typeface tf;
private LayoutInflater mInflater;
private String[] mData = { "button1", "button2", "button3", "button4",
"button5" };
private int[] ids = { R.id.button1, R.id.button2, R.id.button3,
R.id.button4, R.id.button5 };
int[][] rowDrawables = {
{R.drawable.row_1, R.drawable.row_2, R.drawable.row_3,
R.drawable.row_4, R.drawable.row_5},
{R.drawable.row_6, R.drawable.row_7, R.drawable.row_8,
R.drawable.row_9, R.drawable.row_10},
{R.drawable.row_11, R.drawable.row_12, R.drawable.row_13,
R.drawable.row_14, R.drawable.row_15},
{R.drawable.row_16, R.drawable.row_17, R.drawable.row_18,
R.drawable.row_19, R.drawable.row_20},
{R.drawable.row_21, R.drawable.row_22, R.drawable.row_23,
R.drawable.row_24, R.drawable.row_25}};
public MyArrayAdapter(Context context, String[] classes) {
super(context, 0, classes);
mClasses = classes;
mContext = context;
tf = Typeface.createFromAsset(context.getAssets(), "BFantezy.ttf");
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null, true);
holder = new ViewHolder();
holder.textView = (TextView) convertView
.findViewById(R.id.row_label);
holder.textView.setTypeface(tf);
holder.bt1 = (Button) convertView.findViewById(R.id.button1);
holder.bt2 = (Button) convertView.findViewById(R.id.button2);
holder.bt3 = (Button) convertView.findViewById(R.id.button3);
holder.bt4 = (Button) convertView.findViewById(R.id.button4);
holder.bt5 = (Button) convertView.findViewById(R.id.button5);
} else {
holder = (ViewHolder) convertView.getTag();}
String s = mClasses[position];
holder.textView.setText(s);
int[] rowDr = rowDrawables[position];
holder.bt1.setBackgroundResource(rowDr[0]);
holder.bt2.setBackgroundResource(rowDr[1]);
holder.bt3.setBackgroundResource(rowDr[2]);
holder.bt4.setBackgroundResource(rowDr[3]);
holder.bt5.setBackgroundResource(rowDr[4]);
holder.textView.setTag(Integer.valueOf(position));
holder.textView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Integer pos = (Integer) v.getTag();
Intent ourIntent = new Intent(mContext, MyDay.class);
ourIntent.putExtra("cheese", mClasses[pos]);
mContext.startActivity(ourIntent);
}
});
holder.bt1.setTag(Integer.valueOf(position));
holder.bt1.setOnClickListener(mListener);
holder.bt2.setTag(Integer.valueOf(position));
holder.bt2.setOnClickListener(mListener);
holder.bt3.setTag(Integer.valueOf(position));
holder.bt3.setOnClickListener(mListener);
holder.bt4.setTag(Integer.valueOf(position));
holder.bt4.setOnClickListener(mListener);
holder.bt5.setTag(Integer.valueOf(position));
holder.bt5.setOnClickListener(mListener);
return convertView;
}
static class ViewHolder {
TextView textView;
Button bt1, bt2, bt3, bt4, bt5;
}
private OnClickListener mListener = new OnClickListener() {
public void onClick(View v) {
Integer realPos = (Integer) v.getTag();
int video = 0;
String night = null;
for (int i = 0; i < ids.length; i++) {
if (v.getId() == ids[i]) {
video = i;
break;
}
}
Intent i = new Intent(mContext, My_videos.class);
i.putExtra("video", video);
i.putExtra("row", realPos);
mContext.startActivity(i);
}
};
}
ListButtons:
public class ListButtons extends ListActivity {
String classes[] = {"First", "Second", "Third","Fourth", "Fifth" };
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new MyArrayAdapter(this, classes)); }}

how to listen on click of a button in array adapter

I am adding one button per row to show off map in that row in array adapter . I want to get hold of value in that row when that button is clicked . How can I get those values on click of button .
my class:
public class MyListAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<HashMap<String, ArrayList<String>>> pjclist;
private final ArrayList<PermJorneyCycleBean> pjcarraylist ;
String villagename;
int black = Color.WHITE;
float village = 20f;
float depot = 16f;
int red = Color.RED;
int count;
ArrayList<String> Deoptname;
public MyListAdapter(Context context,ArrayList<HashMap<String, ArrayList<String>>>pjcretrivelist, String [] villagename,ArrayList<PermJorneyCycleBean>itempjcarraylist) {
// public MyListAdapter(Context context,ArrayList<PermJorneyCycleBean> pjcretrivelist, String [] villagename) {
super(context, R.layout.scheduleplan,villagename);
this.context = context;
this.pjcarraylist=itempjcarraylist;
this.pjclist=pjcretrivelist;
count =pjcretrivelist.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowView1=null;
LinearLayout rowView=null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (position<count){
rowView1= (LinearLayout) inflater.inflate(R.layout.scheduleplan, null, true);
rowView= (LinearLayout) rowView1.findViewById(R.id.plan);
HashMap<String, ArrayList<String>> depotlistnew = new HashMap<String, ArrayList<String>>();
depotlistnew = pjclist.get(position);
Iterator<Entry<String, ArrayList<String>>> itr = depotlistnew.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry pairs = (Map.Entry) itr.next();
villagename = pairs.getKey().toString();
createNewRow(rowView, villagename, black, village);
Deoptname = (ArrayList) pairs.getValue();
for (int i = 0; i < Deoptname.size(); i++) {
String depotname = new String();
depotname = Deoptname.get(i);
createNewRow(rowView, depotname, red, depot);
}
}
Button mapbutton = createbutton(rowView, "Locate on Map");
mapbutton.setTag(position);
mapbutton.setClickable(true);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to depot map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count){
rowView1 = (LinearLayout) inflater.inflate(R.layout.schedulemap, null, true);
Button villagebutton = (Button)rowView1.findViewById(R.id.getBack);
villagebutton.setClickable(true);
villagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "This is for Map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count+1)
{
rowView1 = (LinearLayout) inflater.inflate(R.layout.scheduleplanlast, null, true);
Button backbutton = (Button)rowView1.findViewById(R.id.getBackHome);
backbutton.setClickable(true);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to test it",Toast.LENGTH_LONG).show();
}
});
}
return rowView1;
}
public void createNewRow(LinearLayout ll1, String value, Integer color,float size) {
TextView tv = new TextView(ll1.getContext());
tv.setTextColor(color);
tv.setTextSize(size);
tv.setText(value);
ll1.addView(tv);
}
public Button createbutton(LinearLayout ll1, String value) {
Button backbutton = new Button(ll1.getContext());
backbutton.setText(value);
backbutton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(backbutton);
return backbutton;
}
public TextView createTextView(LinearLayout ll1, String value){
TextView lattextview = new TextView(ll1.getContext());
lattextview.setVisibility(0);
lattextview.setText(value);
lattextview.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(lattextview);
return lattextview;
}
}
I am not able to get hold of position on click of those buttons .
For your reference i have the following code snippet for button click on Array Adapter
class MySimpleArrayAdapter extends ArrayAdapter<String> {
private Context context;
public MySimpleArrayAdapter(Context context) {
super(context, R.layout.buddy_list);
this.context = context;
}
public int getCount() {
return speedList.size();
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.speeddial_list, null);
}
TextView name = (TextView) rowView.findViewById(R.id.Name);
TextView buddyId = (TextView) rowView.findViewById(R.id.sipid);
Button btn = (Button)rowView.findViewById(R.id.speeddialbtn);
name.setText(speedList.get(position).getName());
buddyId.setText(speedList.get(position).getNumber());
btn.setText(Integer.toString(speedList.get(position).getSPDIndex()));
/*name.setText(names.get(position).toString());
buddyId.setText(buddyIds.get(position).toString());
btn.setText(numberButton.get(position).toString());*/
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (!speedList.get(0).getName().equals(" No SpeedDial Found")) {
registerForContextMenu(getListView());
getListView().showContextMenu();
} else {
unregisterForContextMenu(getListView());
}
selected_name_fromlist = speedList.get(position).getName();
selected_number_fromlist = speedList.get(position).getNumber();
System.out.println(" selected :" + selected_name_fromlist);
}
});
return rowView;
}
}
Here is a good Handling Button clicks in a ListView Row tutorial.

My ListView consist an ImageView and a TextView i need to get the Text from the TextView

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..

Categories

Resources