Set onclick button in listview android

I have a listView with a list item like this.

enter image description here

I want to set an action on the "Edit" and "Remove" buttons.

this is my code.

listitem.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:padding="5dp"
    android:orientation="vertical" >

   <TextView 
       android:id="@+id/varId"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"  
       android:visibility="gone"    
       />

   <TextView
       android:id="@+id/varNoNota"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:textSize="20dp"
       android:textStyle="bold"
       android:padding="2dp"
       />

   <TextView
       android:id="@+id/varSenderName"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/varNoNota"
       android:padding="2dp"
       />

   <TextView
       android:id="@+id/varTotalAmount"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@+id/varSenderName"
       android:padding="2dp"
       />    

   <Button
       android:id="@+id/btnEdit"
       android:layout_width="100dp"
       android:layout_height="30dp"
       android:layout_alignParentRight="true"
       android:layout_alignParentTop="true"
       android:background="@color/YellowGreen"
       android:text="@string/Edit"
       />

   <Button
       android:id="@+id/btnDelete"
       android:layout_width="100dp"
       android:layout_height="30dp"       
       android:layout_alignParentRight="true"
       android:layout_alignBottom="@+id/varTotalAmount"
       android:layout_alignRight="@+id/varTotalAmount"
       android:background="@color/Red"
       android:text="@string/Delete" />

</RelativeLayout >

      

this is resigteritem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:background="@color/LimeGreen">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/registerItem"
        android:textSize="20sp" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"       
        android:padding="5dip"
        android:text="@string/from" />

    <EditText
        android:id="@+id/dateFrom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="25dp" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:padding="5dip"
        android:text="@string/to" />

    <EditText
        android:id="@+id/dateTo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="25dp" />

    <Button
        android:id="@+id/btnSearchRegisterItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:background="@color/YellowGreen"
        android:text="@string/search" />

    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="10dp"
        android:background="@color/DarkGray">

        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"          
            android:layout_height="fill_parent"    
            android:layout_margin="5dp"    
            android:layout_below="@+id/btnSearchRegisterItem"
        />
    </LinearLayout>  

</LinearLayout>

      

this is my code in java file.

public class registerItem extends Activity {

    private Context context = this;

    private EditText dateFrom;
    private EditText dateTo;
    private Calendar c = Calendar.getInstance();
    private int day = c.get(Calendar.DAY_OF_MONTH);
    private int month = c.get(Calendar.MONTH);
    private int year = c.get(Calendar.YEAR);
    private static String url = "http:localhost:8080/exdar/api/registerItem/list";
    private static final String RegisterItemList = "registerItemList";
    private static final String NoNota = "noNota";
    private static final String SenderName = "senderName";
    private static final String TotalAmount = "totalAmount";
    private static final String ID = "id";
    private boolean isFrom = false;
    private Button btnSubmit;
    private Button btnDelete;
    private Button btnEdit;
    ListView list;
    private static String content ;
    private static String from;
    private static String to;

    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();


    private DatePickerDialog.OnDateSetListener dateSetListener = new OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            String finalDate = pad(dayOfMonth) + "/" + pad(monthOfYear + 1)
                    + "/" + year;
            if (isFrom) {
                dateFrom.setText(finalDate);
            } else {
                dateTo.setText(finalDate);
            }
        }

        public String pad(int data) {
            if (data < 10) {
                return "0" + data;
            } else {
                return String.valueOf(data);
            }
        }
    };

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        if (id == 1) {
            return new DatePickerDialog(context, dateSetListener, year, month,
                    day);
        }
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.registeritem);

        setUpView();

        list = (ListView) findViewById(R.id.list);

    }

    private void setUpView() {
        // TODO Auto-generated method stub
        dateFrom = (EditText) findViewById(R.id.dateFrom);
        dateTo = (EditText) findViewById(R.id.dateTo);
        btnSubmit = (Button) findViewById(R.id.btnSearchRegisterItem);
        btnEdit = (Button) findViewById(R.id.btnEdit);
        btnDelete = (Button) findViewById(R.id.btnDelete);

        btnSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                oslist.clear();

                System.out.println("before JSON parse .........!!!!");
                new JSONParse().execute();
                System.out.println("after JSON parse .........!!!!");

            }
        });



        dateFrom.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog(1);
                isFrom = true;
            }
        });
        dateTo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog(1);
                isFrom = false;
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    private class JSONParse extends AsyncTask<Void, Void, Void>{
        private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pDialog = new ProgressDialog(registerItem.this);
            pDialog.setMessage("Getting List Item ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

            System.out.println("masuk on preexecute");

        }

        @Override
        protected Void doInBackground(Void... params) {
            System.out.println("masuk doin background");
            SimpleDateFormat dateparse = new SimpleDateFormat("dd/MM/yyyy");
            HttpUtils networkGet = HttpUtils.getInstance();
            System.out.println("networkGet = "+networkGet);
            from = dateFrom.getText().toString();       
            System.out.println("from = "+from);
            to = dateTo.getText().toString();
            System.out.println("to = "+to);




            try {

                try{                        
                        ArrayList<NameValuePair> parameter = new ArrayList<NameValuePair>();
                        parameter.add(new BasicNameValuePair("from", from));
                        parameter.add(new BasicNameValuePair("to", to));
                        content = MyHttpURLConnection.postToHTTPJSON(url,parameter);
                    }
                    catch(Exception e){
                        System.out.print(e);
                    }
                // Getting JSON Object from URL Content
                JSONObject json = new JSONObject(content);              
                JSONArray jsonArray = json.getJSONArray(RegisterItemList);
                for (int i = 0; i < jsonArray.length(); i++) 
                {
                    System.out.println("looping ke = "+i);
                    JSONObject c = jsonArray.getJSONObject(i);
                    System.out.println("c = "+c);
                    // Storing JSON item in a Variable
                    String id = c.getString(ID);
                    System.out.println("id "+id);
                    String noNota = c.getString(NoNota);
                    System.out.println("noNota = "+noNota);
                    String senderName = c.getString(SenderName);
                    System.out.println("senderName = "+senderName);
                    String totalAmount = c.getString(TotalAmount);
                    System.out.println("totalAmount = "+totalAmount);
                    // Adding value HashMap key => value
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(ID,id);
                    map.put(NoNota, noNota);
                    map.put(SenderName, senderName);
                    map.put(TotalAmount, totalAmount);
                    oslist.add(map);
                    System.out.println("oslist = "+oslist);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            pDialog.dismiss();

            list.setAdapter(new customadapter(oslist,getApplicationContext()));

            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    Toast.makeText(
                            registerItem.this,
                            "You Clicked at "
                                    + oslist.get(+position).get(NoNota),
                            Toast.LENGTH_SHORT).show();
                }
            });
        }       
    }       
}

      

I tried adding this code to check if my code is working correctly and then there will be a toast, but I got an error;

i got this error

enter image description here

I am trying to create a basic adapter.

package com.example.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class customadapter extends BaseAdapter{ 

    ArrayList<HashMap<String, String>> oslist;
    Context context;
    private Button btnDelete;
    private Button btnEdit;

    public customadapter(ArrayList<HashMap<String, String>> oslist, Context context) {      
        context = context;
        oslist = oslist;
        this.oslist = oslist;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        System.out.println("oslist.size() = "+oslist.size());
        return oslist.size();
    }

    @Override
    public Map.Entry<String, String> getItem(int position) {
        // TODO Auto-generated method stub
        return (Map.Entry) oslist.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater lif = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = lif.inflate(R.layout.listitem, null);

        TextView txt_Name = (TextView) convertView.findViewById(R.id.varId);
        Button btnEdit = (Button) convertView.findViewById(R.id.btnEdit);

        btnEdit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                System.out.println("mybutton in listview already works!!");
                 //Here perform the action you want             
            }

        });

        return convertView;
    }

}

      

-1


source to share


4 answers


Try to use BaseAdapter instead of ListAdapter, it will be easier

Here I give a sample code that you can implement in this code,



public class BaseAdapContact extends BaseAdapter {

List<String> liName;
Context con;

public BaseAdapContact(List<String> liName, Context con) {
    this.liName = liName;
    this.con = con;
}

@Override
public int getCount() { // TODO Auto-generated method stub
    return liName.size();
}

@Override 
public Object getItem(int position) { 

    return null; 
}

@Override 
public long getItemId(int position) { 

    return 0; 
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater lif = (LayoutInflater) con
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = lif.inflate(R.layout.list_view, null);

    TextView txt_Name = (TextView) convertView.findViewById(R.id.txtName);
    Button btn_Call = (Button) convertView.findViewById(R.id.btnCall);

    txt_Name.setText(liName.get(position));

    btn_Call.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

             //Here perform the action you want             
        }

    });

    return convertView;
}

}

      

+2


source


According to my aspect you should have initialized

your list insetUpView();

 list = (ListView) findViewById(R.id.list);

      

Your application breaks down into



  list.invalidateViews();
  list.setAdapter(adapter);

      

in onPostExecute(Void result)

on this linelist==null

+1


source


Where is your adapter list?

You must set onClickListner

to a button inside your list adapter

0


source


you must use the interface to listen to the Click Event.

Here's an example,

First you need to create an interface in an adapter.

public interface onListItemClickListener{
    void onEditClick();
    void onDeleteClick();
}

      

And then implement onListItemClickListener in your registerItem activity . You will need to implement two methods in your activity.

in the click event from your adapter, for ex

btn_edit.setOnClickListener(new OnClickListener() {

    @Override 
    public void onClick(View v) {

         //you will contain Context from your parent activity
         //cast your context to listener coz it implement that listener
         onListItemClickListener listener = (onListItemClickListener) mContext;

         // you can add parameter in method
         listener.onEditClick();
         //Done this will call your method in your activity.
    } 

}); 

      

Hope this helps you.

0


source







All Articles