-1

i have a listView with list item like this.

enter image description here

i want to set an action at button "Edit" and "Delete".

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 at file java.

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 add this code to see if my code run with correctly then the toast will be show but i got error;

i got this error

enter image description here

i am trying to create a baseadapter..

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;
    }

}
  • the problem i think is that you are in view resigteritem.xml where your list view is and you are using click listener on listitem.xml, i suggest you to inflate the view and then implement the click listeners or make custom adapter and on its getView add click listner – Syed Raza Mehdi May 07 '15 at 05:03
  • @SyedRazaMehdi listview implement click listener? –  May 07 '15 at 05:09
  • no that is the whole one view item click, you need separate button click so you need to get the view from adapter of every item and then implement the click listener on that, what i do is to make a custom adapter and then implement click listener in it's getView – Syed Raza Mehdi May 07 '15 at 05:21
  • see this https://tausiq.wordpress.com/2012/08/22/android-listview-example-with-custom-adapter/ – Syed Raza Mehdi May 07 '15 at 05:22

4 Answers4

1

As per my aspect you should initialized your list in setUpView();

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

Your app is crash at

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

in onPostExecute(Void result) at this line list==null

M D
  • 47,665
  • 9
  • 93
  • 114
1

Try to use BaseAdapter Instead of ListAdapter it will be easier

Here i'm giving sample code you can implement like this in your 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;
}

}
Sahil Garg
  • 263
  • 1
  • 20
0

Where is your list adapter???

You should set onClickListner on a button inside your list adapter

Salmaan
  • 3,543
  • 8
  • 33
  • 59
  • i set this code btnDelete.setOnClickListener(new OnClickListener() , but ii still get that error –  May 07 '15 at 05:03
0

you should use interface to listen Click Event.

Here is example,

First, you need to create a interface in adapter.

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

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

in 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 will help you.

Hein Htet Aung
  • 844
  • 4
  • 16