get data from Intent Activity and button activated in ListView - android

Hi thanks for reading this! Please help me.
I am trying to create a restaurant app which the display 3 buttons in the menu then click the food button which display the list of food, then customer can choose the food they want to order then send back the order back to first page. I read a lot of the article and some say use the listview.setItemsCanFocus(true) but I having problem to understand it to implement it. and some say the button listener inside the getView but when I implement my program just hang. Please help me. Thank you.
my menu :
here is my food(second) page
I am having problems:
to transfer the data back from the food.class back to my main class which is
restaurant.class
After I add the button in the list the food is not clickable(the whole row of food).
my main class(restaurant)
public class SesameRestaurant extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void foodMenu(View v){
startActivity(new Intent(SesameRestaurant.this,Food.class));
//setContentView(R.layout.foods);
}
public void drinkMenu(View v){startActivity(new Intent(SesameRestaurant.this,Drink.class));}
public void billMenu(View v){}
}
my second class (food.class)
package com.restaurant.sesame;
public class Food extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static final String[] title = new String[] {
"Cow Rib steak",
"Thai Prawn Fried Rice",
"Christmas Sensation Delight",
"Salmon Steak" };
static final String[] detail = new String[] {
"1h 37m Shipping: $10.00",
"1h 39m Shipping: Free",
"58m 6s Shipping: $10.00",
"59m 30s Shipping: $10.95" };
private Integer [] imgid = { R.drawable.food1, R.drawable.food2, R.drawable.food3, R.drawable.food4 };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.foods);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
rd = new RowData(i,title[i],detail[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Log.w("my app", "Click list Item!!!");
Toast.makeText(getApplicationContext(), "You have selected "+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
public void orderClick(View v){
}
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
RowData(int id,String title,String detail)
{
mId=id;
mTitle = title;
mDetail=detail;
}
#Override
public String toString() {
return mId+" "+mTitle+" "+mDetail;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
detail = holder.getdetail();
detail.setText(rowData.mDetail);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail() {
if(null == detail){
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
public void backClick(View v){
finish();
}
}
my food menu interface foods.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_height="wrap_content"
android:text="Back"
android:onClick="backClick"
android:layout_width="fill_parent">
</Button>
my list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="#+id/img"
android:scaleType="centerCrop"
android:layout_width="100dp"
android:layout_height="100dp"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:id="#+id/title"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#ffffff"
android:textSize="16sp" />
<TextView
android:layout_width="fill_parent"
android:id="#+id/detail"
android:textColor="#ffffff"
android:layout_height="wrap_content"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity :"
android:textColor="#ffffff" />
<EditText
android:id="#+id/quantityInput"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_toRightOf="#id/quantity"
android:hint="1-10"
android:paddingLeft="10dp"
android:textSize="12dp" />
<Button
android:id="#+id/order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="120dp"
android:layout_toRightOf="#id/quantity"
android:onClick="orderClick"
android:text="Order"
android:textSize="12dp" />
</RelativeLayout>
</LinearLayout>

I'm at school now so I don't have time to get a you a code snippet at all but you are going to need to use startActivityForResult() instead of just startActivity(). This will allow you to send information back to your main app upon completion of the your food activity.
Respond if you need me to find a snippet for you and I'll write one up quick once I get home in about an hour.

Related

Multiple radio-buttons in listview gets selected even if I select one button after scrolling

I have a list of cards-views which I am rendering, in each card there is information about that particular route and radio button which when clicked
should give me the position of the route form the complete list of routes
when clicked on different radio button previous one should be toggled and the one selected should be selected
Problem I am facing
when I select lets say 3rd radio button it selects 3rd items when the list renders the next views which is how the arrayadapter works. even though In my listview I have used android:choiceMode="singleChoice" still its not selecting single radio button.
Here is the image also go see what the problem is exactly
my RouteAdapter class whee I am trying to check which radio-button is pressed
class RouteAdapter extends ArrayAdapter<RouteItem> {
private Context mContext;
RouteAdapter(Activity context, List<RouteItem> routes) {
super(context, 0, routes);
this.mContext = context;
}
#NonNull
#Override
public View getView(final int position, final View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
// we are passing false as we don't want to attach it to view just yet,
// first set the proper name and details then set it.
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.route_view, parent, false);
}
// getting the route at that position
RouteItem route = getItem(position);
......
final RadioButton rb = (RadioButton) listItemView.findViewById(R.id.radio_button);
//todo: fix radio button to save prefs
rb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RouteItem route = getItem(position);
Log.d("RouteAdapter.class", "getView: "+ route.getRoute_id());
rb.toggle();
}
});
return listItemView;
}
}
my activity_view_route.xml where I am rendering all the routeItems
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/add_route"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true"
android:choiceMode="singleChoice"
tools:context="com.sjain.routeplanner.ViewRouteActivity" />
<TextView
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAppearance="?android:textAppearanceMedium" />
<ProgressBar
android:id="#+id/loading_indicator"
style="#style/Widget.AppCompat.ProgressBar"
android:indeterminateTint="#color/teal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
here is my route_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_centerHorizontal="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/route_name"
android:id="#+id/view_name"
android:textSize="20sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:text="#string/endpoints"
android:id="#+id/view_start"
android:textSize="18sp"
android:layout_below="#id/view_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:text="#string/view_waypoints"
android:id="#+id/waypoints"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_below="#id/view_start"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:text="#string/endpoints"
android:id="#+id/view_end"
android:textSize="18sp"
android:layout_below="#id/waypoints"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radio_button"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/view_map"
android:padding="8dp"
android:background="#color/com_facebook_blue"
android:layout_alignBottom="#id/view_end"
android:layout_alignParentEnd="true"
android:layout_marginEnd="7dp"
android:text="#string/view_map"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/view_id"
android:visibility="gone"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
My routeItem class
class RouteItem {
private String route_name;
private String start_point;
private String end_point;
private String route_id;
private ArrayList<String> waypoints;
private ArrayList<String> waypoint_name;
RouteItem(String route_name, String route_id, String start_point, String end_point, ArrayList<String> waypoints, ArrayList<String> waypoint_name) {
this.route_name = route_name;
this.route_id = route_id;
this.start_point = start_point;
this.end_point = end_point;
this.waypoints = waypoints;
this.waypoint_name = waypoint_name;
}
String getRoute_name() {
return route_name;
}
String getStart_point() {
return start_point.split(";")[0];
}
String getEnd_point() {
return end_point.split(";")[0];
}
String getEnd_point_coordinate() {
return end_point.split(";")[1];
}
String getStart_point_coordinate() {
return start_point.split(";")[1];
}
String getRoute_id() {
return route_id;
}
ArrayList<String> getWaypoints() {
return waypoints;
}
ArrayList<String> getWaypoint_name() {
return waypoint_name;
}
}
I know there is something like radio-group also but that seems to be out of option here since the list is generated dynamically depending on the number of routes obtained form the server. My problem is similar to this question Android Radio buttons in a custom listview changes its state when we scroll the list but this is also not properly answered.
If someone can please let me know how to fix this issue and just get the position of the card which is selected.
Ok. First of all change your RouteItem class as :
class RouteItem {
private String route_name;
private String start_point;
private String end_point;
private String route_id;
private ArrayList<String> waypoints;
private ArrayList<String> waypoint_name;
private String radioButtonState = "unSelected";
RouteItem(String route_name, String route_id, String start_point, String end_point, ArrayList<String> waypoints, ArrayList<String> waypoint_name) {
this.route_name = route_name;
this.route_id = route_id;
this.start_point = start_point;
this.end_point = end_point;
this.waypoints = waypoints;
this.waypoint_name = waypoint_name;
}
String getRoute_name() {
return route_name;
}
String getStart_point() {
return start_point.split(";")[0];
}
String getEnd_point() {
return end_point.split(";")[0];
}
String getEnd_point_coordinate() {
return end_point.split(";")[1];
}
String getStart_point_coordinate() {
return start_point.split(";")[1];
}
String getRoute_id() {
return route_id;
}
ArrayList<String> getWaypoints() {
return waypoints;
}
ArrayList<String> getWaypoint_name() {
return waypoint_name;
}
public String getRadioButtonState() {
return radioButtonState;
}
public void setRadioButtonState(String radioButtonState) {
this.radioButtonState = radioButtonState;
}
}
Now update your adapter.
class RouteAdapter extends ArrayAdapter<RouteItem> {
private Context mContext;
List<RouteItem> routes;
RouteAdapter(Activity context, List<RouteItem> routes) {
super(context, 0, routes);
this.mContext = context;
this.routes = routes;
}
#NonNull
#Override
public View getView(final int position, final View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
// we are passing false as we don't want to attach it to view just yet,
// first set the proper name and details then set it.
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.route_view, parent, false);
}
// getting the route at that position
RouteItem route = getItem(position);
......
final RadioButton rb = (RadioButton) listItemView.findViewById(R.id.radio_button);
//todo: fix radio button to save prefs
if(route.getRadioButtonState().equals("unSelected")){
rb.setSelected(false);
}
else{
rb.setSelected(true);
}
rb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RouteItem route = getItem(position);
Log.d("RouteAdapter.class", "getView: "+ route.getRoute_id());
rb.toggle();
if(rb.isSelected()){
route.setRadioButtonState("selected");
}
else {
route.setRadioButtonState("unSelected");
}
for(int i=0; i<routes.size(); i++){
if(i != position){
routes.get(i).setRadioButtonState("unSelected");
}
}
notifyDataSetChanged();
}
});
return listItemView;
}
}

Android - SetOnItemClickListener doesn't work

I know here we have a lot of questions like mine, but I don't know why none works for me.
My objective: I have an AlertDialog with a ListView with a check box in each row, I can select some of the items, and I wish to make an ArrayList with the elements selected.
For that reason, I'm calling the SetOnclickListener, I put a Log inside the method, but does nothing.
I tried with focusable and clickable almost everywhere, but my Log doesn't appear.
Here My alert Dialog
private void callAdditionalDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(ConfigProductActivity.this);
final View additionalView = layoutInflater.inflate(R.layout.dialog_additional, null);
additionalView.setFocusable(true);
// set the custom dialog components - text, buttons, accountants
TextView titleDialog = (TextView) additionalView.findViewById(R.id.title_additional);
titleDialog.setTypeface(boldFont);
Button buttonAccept = (Button) additionalView.findViewById(R.id.button_accept);
buttonAccept.setTypeface(boldFont);
Button buttonCancel = (Button) additionalView.findViewById(R.id.button_cancel);
buttonCancel.setTypeface(boldFont);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ConfigProductActivity.this);
alertDialogBuilder.setView(additionalView);
final AlertDialog alertD = alertDialogBuilder.create();
alertD.setCanceledOnTouchOutside(false);
//Fill object of additional
final ListView additionalListView = (ListView) additionalView.findViewById(R.id.list_additional);
TextView additionalNotFound = (TextView) additionalView.findViewById(R.id.additional_not_found);
if (!withoutModifiers){
additionalAdapter = new AdditionalAdapter(ConfigProductActivity.this, additionalList);
additionalListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
additionalListView.setAdapter(additionalAdapter);
final ArrayList<ModifierEntity> modifierList = new ArrayList<ModifierEntity>();
additionalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Object modifier = additionalListView.getAdapter().getItem(position).toString();
Log.d(TAG, "SOMETHIIIIING");
}
});
}
else{
additionalListView.setVisibility(View.GONE);
additionalNotFound.setVisibility(View.VISIBLE);
additionalNotFound.setTypeface(font);
buttonCancel.setVisibility(View.GONE);
}
//End of fill object of additional
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
buttonAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//additional.setText(additionalAdapter.getCount());
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
alertD.show();
}
Here my adapter:
public class AdditionalAdapter extends ArrayAdapter {
private static String TAG = AdditionalAdapter.class.getName();
private List<ModifierEntity> originalData = null;
private ConfigProductActivity activity;
private Typeface font;
private Typeface boldFont;
private static ModifierEntity modifier;
public AdditionalAdapter (ConfigProductActivity activity, List<ModifierEntity> listArray){
super(activity, R.layout.additional_item);
this.activity = activity;
this.originalData = listArray ;
font = Typeface.createFromAsset(activity.getAssets(),"HelveticaNeueThn.ttf");
boldFont = Typeface.createFromAsset(activity.getAssets(), "avgardm.ttf");
}
public static class Row
{
public TextView labelName;
public TextView labelPrice;
public CheckBox check;
}
#Override
public int getCount() {
return originalData.size();
}
#Override
public ModifierEntity getItem(int position) {
return originalData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int colorFont = activity.getResources().getColor(R.color.brown_tataki);
final Row holder;
View rowView = convertView;
// reuse views
if (convertView == null) {
holder = new Row();
LayoutInflater inflater = LayoutInflater.from(activity);
rowView = inflater.inflate(R.layout.additional_item, null);
rowView.setClickable(true);
//rowView.setFocusable(false);
// configure view holder
holder.labelName = (TextView) rowView.findViewById(R.id.additional_name);
holder.labelPrice = (TextView) rowView.findViewById(R.id.additional_price);
holder.check = (CheckBox) rowView.findViewById(R.id.additional_check);
rowView.setTag(holder);
}
else {
holder = (Row) convertView.getTag();
// rowView.setClickable(true);
}
final ModifierEntity itm = originalData.get(position);
holder.labelName.setText(itm.getModifier_name());
holder.labelName.setTypeface(font);
holder.labelName.setTextColor(colorFont);
holder.labelPrice.setText(GlobalParameters.CURRENCY.concat(String.valueOf(itm.getModifier_cost())));
holder.labelPrice.setTypeface(boldFont);
holder.labelPrice.setTextColor(colorFont);
return rowView;
}
}
Here My Dialog
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/orange_tataki"
android:text="#string/additional_title"
android:textColor="#color/white"
android:textSize="20sp"
android:gravity="center"
android:id="#+id/title_additional"
android:padding="5dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title_additional"
android:gravity="center"
android:background="#color/white"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_additional"
android:divider="#color/brown_tataki"
android:dividerHeight="0.5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/list_additional"
android:gravity="center"
android:padding="10dp"
android:visibility="gone"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_not_found"
android:text="#string/additional_not_found"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttons"
android:layout_marginBottom="10dp"
android:layout_below="#+id/additional_not_found"
android:gravity="center"
android:layout_marginTop="20dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/button_cancel"
android:background="#color/green_tataki"
android:text="#string/button_cancel"
android:textSize="15sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_accept"
android:padding="10dp"
android:background="#color/green_tataki"
android:text="#string/button_accept"
android:textSize="15sp"
android:layout_marginLeft="15dp"
/>
</LinearLayout>
</RelativeLayout>
And Here my item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="QUESO"
android:singleLine="true"
android:padding="10dp"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/additional_price"
android:padding="10dp"
android:text="Bs. 500"
android:textColor="#color/brown_tataki"
android:layout_toRightOf="#id/additional_name"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:id="#+id/additional_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp" />
Using interfaces I can solve my problem, this link provided me the solution, and bassically consist in create an interface and implement in my activity.
Like this:
1.- Interface
public interface MyListener {
void folderClicked();
}
2.- Implements the interface in the activity
public class ActivityA extends Activity implements MyListener
3.- You will have to auto override the method folderClicked it will look like this:
#Override
protected void folderClicked() {
// Do your stuff here.
}
4.- Send the activity listener to the adapter with constructor like this:
MyAdpater adapter = new MyAdpater(ActivityA.this);
5.- Your adapter class your code should be like this:
public class TimeLineAdapter extends BaseAdapter {
private MyListener mListener;
public TimeLineAdapter(MyListener listener) {
super();
mListener = listener;
}
holder.iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onFolderClicked()
//code to do stuff when the image is clicked
}

remove items from listview by pressing delete button android

I want to delete my listview items when I press delete button but the problem is I should first press listview row then press delete button to remove it. I want to delete items immediately after pressing delete button not first press on listview then press delete button
Can you help me in this situation?
and this is my code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wholeshop);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// getting values from selected ListItem
final View view = v;
final int pos =position;
deleteone= (Button)v.findViewById(R.id.bdeleteone);
deleteone.getTag(position);
deleteone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
deleteone.setTag(view);
productsList.remove(pos);
ListAdapter adapter = new SimpleAdapter(
wholeShop.this, productsList,
R.layout.listshop, new String[] { "name",
"spinn","price"},
new int[] { R.id.wholename, R.id.wholespinn,R.id.wholeprice });
// updating listview
setListAdapter(adapter);
}
});
}
});
}
and this is my xmlfile for listview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#ffffff">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="110dp"
android:layout_marginTop="50dp"
android:descendantFocusability="blocksDescendants"
>
</ListView>
and:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#ffffff"
android:weightSum="100">
<TextView
android:id="#+id/wholename"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="40"
android:paddingLeft="5dip"
android:text="Flower Name"
android:textColor="#000000" />
<TextView
android:id="#+id/wholespinn"
android:layout_width="66dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="2dp"
android:paddingRight="10dip"
android:text="Flower spinn"
android:textColor="#000000"
android:layout_weight="30"/>
<TextView
android:id="#+id/wholeprice"
android:text="Flower price"
android:layout_gravity="right"
android:paddingRight="10dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:layout_weight="30"/>
<Button
android:id="#+id/bdeleteone"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Del"
android:layout_marginRight="10dp"
android:layout_weight="30"
android:focusable="false"
/>
</LinearLayout>
You are going with wrong way.
You may have to look this Example.
You have create Your Own Adapter like:
public class ListAdapter extends ArrayAdapter<String> {
customButtonListener customListner;
public interface customButtonListener {
public void onButtonClickListner(int position,String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
private ArrayList<String> data = new ArrayList<String>();
public ListAdapter(Context context, ArrayList<String> dataItem) {
super(context, R.layout.child_listview, dataItem);
this.data = dataItem;
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.child_listview, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView
.findViewById(R.id.childTextView);
viewHolder.button = (Button) convertView
.findViewById(R.id.childButton);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String temp = getItem(position);
viewHolder.text.setText(temp);
viewHolder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position,temp);
}
}
});
return convertView;
}
public class ViewHolder {
TextView text;
Button button;
}
}

Items of ListView in ListActivity remain unclickable

In my app there is a Main Acitvity (which extends List Activity) where I have one list view. I want to make items of this list view clickable and handle click events. Here's my code:
public class MainActivity extends ListActivity {
private ArrayList<Item> m_parts = new ArrayList<Item>();
private ItemAdapter m_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
(…)
m_adapter = new ItemAdapter(this, R.layout.item_layout, m_parts);
setListAdapter(m_adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
(…)
}
}
And here's my xml for Main Activity layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/main_background"
tools:context=".MainActivity">
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
</ListView>
</LinearLayout>
This is my Item class:
public class Item {
private Bitmap image;
private Uri uri;
private String title;
private String date;
private String latitude;
private String longitude;
public CheckBox checkBox = null;
public Item(){}
public Item(Bitmap bi, Uri ur, String ti, String da, String la, String lo){
this.image = bi;
this.uri = ur;
this.title = ti;
this.date = da;
this.latitude = la;
this.longitude = lo;
}
public Bitmap getImage() {return image;}
public String getTitle(){
return title;
}
public String getDate(){
return date;
}
public String getLatitude(){
return latitude;
}
public String getLongitude(){
return longitude;
}
public Boolean isChecked(){
return checkBox.isChecked();
};
public Uri getUri(){
return uri;
}
}
Item's layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight">
<ImageView
android:id="#+id/photo"
android:layout_width="60dp"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/place"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/photo"
android:textColor="#color/white"
android:textColorHighlight="#color/white"
android:textColorHint="#color/white"
android:textColorLink="#color/white"
android:hint="#string/founding_place_text" />
<TextView
android:id="#+id/date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/photo"
android:textColor="#color/white"
android:textColorHighlight="#color/white"
android:textColorHint="#color/white"
android:textColorLink="#color/white"
android:hint="#string/founding_date_text" />
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/photo"
android:maxLines="1"
android:textColor="#color/white"
android:textColorHighlight="#color/white"
android:textColorHint="#color/white"
android:textColorLink="#color/white"
android:hint="#string/founding_title_text_2" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
And eventually my Item Adapter:
public class ItemAdapter extends ArrayAdapter<Item>{
private ArrayList<Item> objects;
public ItemAdapter(Context context, int textViewResourceId, ArrayList<Item> objects){
super(context, textViewResourceId, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
if(v == null){
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item_layout, null);
}
Item i = objects.get(position);
if(i != null){
ImageView im = (ImageView)v.findViewById(R.id.photo);
TextView ti = (TextView)v.findViewById(R.id.title);
TextView da = (TextView)v.findViewById(R.id.date);
TextView pl = (TextView)v.findViewById(R.id.place);
CheckBox ch = (CheckBox)v.findViewById(R.id.checkBox);
if(im != null){
im.setImageBitmap(i.getImage());
}
if(ti != null){
if(i.getTitle() != null && i.getTitle() != ""){
ti.setText(i.getTitle());
}else{
ti.setText("No title");
}
}
if(da != null){
da.setText(i.getDate());
}
if(pl != null){
if(i.getLatitude()!=null && i.getLongitude()!=null){
pl.setText(i.getLatitude() + ", " + i.getLongitude());
}else{
pl.setText("No coordinates");
}
}
if(ch != null){
i.checkBox = ch;
}
}
return v;
}
}
My problem is that onListItemClick(…) isn't called when I click on any item in list view. What's more, they aren't even highlighted. Do you have any idea what do I have to add to my code to handle click events? I am using Android 4.3.
Don't set your list view to be clickable and don't set an OnItemClickListener. (In other words, end your onCreate() method with the call to setlistAdapter.) You only need to override onListItemClicked; the ListActivity infrastructure takes care of the rest. By setting a listener yourself you are interfering with the framework's mechanism.
remove android:clickable="true" from layout and listView.setClickable(true) from code and set listView.setOnItemClickListener and put android:layout_height="wrap_content" android:layout_width="match_parent

ListView with Add and Delete Buttons in each Row in android

I am developing an android application in which I have made one ListView. I have to add 2 buttons with each row in ListView. These 2 buttons are Add and Delete. When user selects one of the buttons then some actions should be taken. How can I do it?
You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="Add" />
</RelativeLayout>
Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_custom_list_layout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
on delete button click event
public void delete(View v){
ListView listview1;
ArrayList<E> datalist;
final int position = listview1.getPositionForView((View) v.getParent());
datalist.remove(position);
myAdapter.notifyDataSetChanged();
}
Step-1: Create activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0099CC"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Multi Touch Listview"
android:textColor="#FFFFFF"
android:textSize="25sp" />
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/textView"
android:layout_marginTop="5dp"
android:cacheColorHint="#00000000" />
</RelativeLayout>
Step-2 Create row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="User Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="5dp"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp" />
<Button
android:id="#+id/button1"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Edit Data"
android:textColor="#0099CC" />
<Button
android:id="#+id/button2"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Delete"
android:textColor="#0099CC" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="5dp"
android:text="Location" />
</RelativeLayout>
Step-3 Create User.java bean class
public class User {
String name;
String address;
String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public User(String name, String address, String location) {
super();
this.name = name;
this.address = address;
this.location = location;
}
}
Step-4 Create UserCustomAdapter.java
public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}
Step-5 Create MainActivity.java
public class MainActivity extends Activity {
ListView userList;
UserCustomAdapter userAdapter;
ArrayList<User> userArray = new ArrayList<User>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* add item in arraylist
*/
userArray.add(new User("Mumer", "Spain", "Spain"));
userArray.add(new User("Jon", "EW", "USA"));
userArray.add(new User("Broom", "Span", "SWA"));
userArray.add(new User("Lee", "Aus", "AUS"));
userArray.add(new User("Jon", "EW", "USA"));
userArray.add(new User("Broom", "Span", "SWA"));
userArray.add(new User("Lee", "Aus", "AUS"));
/**
* set item into adapter
*/
userAdapter = new UserCustomAdapter(MainActivity.this, R.layout.row,
userArray);
userList = (ListView) findViewById(R.id.listView);
userList.setItemsCanFocus(false);
userList.setAdapter(userAdapter);
/**
* get on item click listener
*/
userList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Log.i("List View Clicked", "**********");
Toast.makeText(MainActivity.this,
"List View Clicked:" + position, Toast.LENGTH_LONG)
.show();
}
});
}
}
You may check my blog for full code. look here-

Categories

Resources