0

Question part: 1

I have created an activity which contains product id and product name as list items. Each row contains an edittext which can be used to enter quantity for a particular product. The rows also contain a checkbox to select the particular product.

This is how the list looks like:

List

When I click on the list items, I can get the id and name of the particular list item, but I also want to get the quantity entered by the user for the list item.

This is the activity responsible for generating the listview:

public class PollStationActivity extends Activity {     

    // Hashmap for ListView
            ArrayList<HashMap<String, String>> PSList = new ArrayList<HashMap<String, String>>();
            String status_code_from_prev;
            List<HashMap<String, String>> fillMaps=null;
            String alert_message;
            String quantity_message;

            //quantity edittext
            EditText quantity_edit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         setContentView(R.layout.activity_poll_station);


         //quantity edittext
         quantity_edit   = (EditText)findViewById(R.id.qty_editText);

        //database insertion
         DatabaseHelper db = new DatabaseHelper(this);
        ContentValues values = new ContentValues();
        try {
         db.createDataBase();
         values.put("_id", "1");
         values.put("name", "rose");
         db.insert(values);

        } catch (IOException e) {
         e.printStackTrace();
          }
        db.close();            


            ArrayList<TestItem> PSList = new ArrayList<TestItem>();            

             try {
              db.createDataBase();

              PSList =  db.getAllData();

             } catch (IOException e) {
              e.printStackTrace();
               }

             db.close();

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

                Iterator<TestItem> i = PSList.iterator();

                while(i.hasNext())
                {
                    HashMap<String, String> map = new HashMap<String, String>();
                    TestItem objPSItem = i.next();

                    map.put("name", objPSItem.NAME);
                    map.put("Id", objPSItem.ID);
                    //map.put("quantity", objPSItem.QUANTITY);
                    fillMaps.add(map);
                }


            Log.i("Size: ", ""+fillMaps.size());
            //populating listview from database
            ListView listView1 = (ListView) findViewById(R.id.poll_list_listView);          


              if (null != listView1 && null != PSList) {
                  listView1.setAdapter(new ListAdapter(PollStationActivity.this,
                 R.id.ListViewContainer, new String[fillMaps.size()]));

              }

    }       


    //class for the list and on click handler
    class ListAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] values;          

        public ListAdapter(Context context, int textViewResourceId,
                String[] objects) {
            super(context, textViewResourceId, objects);
            // TODO Auto-generated constructor stub
            this.context = context;
            this.values = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            // return super.getView(position, convertView, parent);

            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            final View rowView = inflater.inflate(R.layout.list_layout, parent,
                    false);

            final HashMap<String, String> map =  fillMaps.get(position);

            TextView textView = (TextView) rowView
                     .findViewById(R.id.list_label_name);
                     textView.setText("("+map.get("Id")+") "+map.get("name"));          


            rowView.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {

                    rowView.setBackgroundResource(R.drawable.list_bg_pressed);

                    Handler handler = new Handler();
                    Runnable r = new Runnable() {
                        public void run() {
                            rowView.setBackgroundResource(R.drawable.list_bg);

                        }
                    };
                    handler.postDelayed(r, 200);        

                    //alert box
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(PollStationActivity.this);

                     // Setting Dialog Title
                     alertDialog.setTitle("Please Note!");

                     // Setting Dialog Message
                     alertDialog.setMessage("Are you sure you want to select "+"("+map.get("Id")+") "+map.get("name")+"?");


                     // Setting Positive "Yes" Button
                     alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog,int which) {

                         // Write your code here to invoke YES event
//                           Intent intent = new Intent(RegisterFirstActivity.this, RegisterSecondActivity.class);
//                              
//                              intent.putExtra("AC_Code", map.get(TAG_CODE));
//                              RegisterFirstActivity.this.startActivity(intent);

                         }
                     });

                     // Setting Negative "NO" Button
                     alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int which) {
                         // Write your code here to invoke NO event

                         dialog.cancel();
                         }
                     });

                     // Showing Alert Message
                     alertDialog.show();

                }
            });

            return rowView;

        }
    }


    public void makeAToast(String str) {
        //yet to implement
        Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

 }

This is the TestItem class:

 public class TestItem {

public String ID;
public String NAME;
public String QUANTITY;
public boolean selected;

    // Empty constructor
    public TestItem(){

    }
    // constructor
    public TestItem(String id, String name, String quantity){
        this.ID = id;
        this.NAME = name;
        this.QUANTITY = quantity;
    }

    // constructor
    public TestItem(String name, String quantity){
        this.NAME = name;
        this.QUANTITY = quantity;
    }
    // getting ID
    public String getID(){
        return this.ID;
    }

    // setting id
    public void setID(String id){
        this.ID = id;
    }

    // getting name
    public String getName(){
        return this.NAME;
    }

    // setting name
    public void setName(String name){
        this.NAME = name;
    }

    // getting phone number
    public String getQuantity(){
        return this.QUANTITY;
    }

    // setting quantity
    public void setQuantity(String quantity){
        this.QUANTITY = quantity;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

 }

This is the activity_poll_station.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:background="@drawable/main_bg">    


<RelativeLayout
    android:id="@+id/ListViewContainer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/poll_label_textView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="28dp" >

    <ListView
        android:id="@+id/poll_list_listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </ListView>

</RelativeLayout>



    </RelativeLayout>

This is the list_layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/library_linear_layout"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:layout_alignParentLeft="true"
    android:background="@drawable/list_bg"
    android:padding="5dp" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="44dp"
        android:background="@null" >

        <TextView
            android:id="@+id/list_label_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:text="name"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textSize="17sp" />

        <CheckBox
            android:id="@+id/item_checkBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"/>

        <EditText
            android:id="@+id/qty_editText"
            android:layout_width="75dp"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:ems="10"
            android:maxLines="1"
            android:inputType="number" >

        </EditText>

    </RelativeLayout>

</LinearLayout>

I want to how to extract text from the edittext which I have created for every list item. If I try to extract the text on

rowView.setOnClickListener(new View.OnClickListener()

like this:

// Setting Dialog Message
                     alertDialog.setMessage("Are you sure you want to select "+"("+map.get("Id")+") "+map.get("name")+"Quantity: "+quantity_edit.getText().toString()+"?");

The I am getting a null pointer exception getting generated due to the rowView.setOnClickListener(new View.OnClickListener()

What should I do? What should be the work around?

Thanks in advance!

//------------------------------------------------------------------------------//

Question part: 2

Now I want to do something like, I want to remove a particular row on clicking it. The row will only be deleted from the existing listview and a new list will be shown, how to do that?

Thanks once again!

Stanojkovic
  • 1,612
  • 1
  • 17
  • 24
kittu88
  • 2,451
  • 5
  • 40
  • 80

3 Answers3

2

You first need to get the reference to the EditText object, which you can do by using findViewById

quantity_edit = (EditText) view.findViewById("qty_editText");
Waqas
  • 6,812
  • 2
  • 33
  • 50
  • This is done in the oncreate method of the activity class, like this: //quantity edittext quantity_edit = (EditText)findViewById(R.id.qty_editText); – kittu88 Mar 07 '13 at 06:04
  • 2
    And which is WRONG! Since this EditText isn't in activity_poll_station.xml that is why you are getting NULL exception. Try place my suggested piece of code inside onclick event – Waqas Mar 07 '13 at 06:11
  • ok thats done! but I can see that it is only picking the text of the edittext of the first row in the list. but it is not able to pick up the text from any other rows. – kittu88 Mar 07 '13 at 06:22
  • and my answers helped you, would you please mark this as correct answer also :) – Waqas Mar 07 '13 at 06:42
  • change this to (EditText)findViewById(R.id.qty_editText) -> (EditText) v.findViewById(R.id.qty_editText) – Waqas Mar 07 '13 at 06:45
2

you have override getView method of custom adapter. like the following.

public class SimpleAdapter1 extends ArrayAdapter<Data> {

    public SimpleAdapter1(Context context, int textViewResourceId,
            List<Data> catDesc) {
        super(context, textViewResourceId, catDesc);
        this.items = (ArrayList<Data>) catDesc;
        this.context = context;
        itemsid = new ArrayList<Integer>();
        System.out.println(items);
    }

    @Override
    public View getView(final int position, View convertView,
            final ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.YourLayout, null);
        }

        edit = (EditText) v.findViewById(R.id.editText1);
        String tx = edit.getText().toString();
                return v;
       }
    }
kittu88
  • 2,451
  • 5
  • 40
  • 80
Gunaseelan
  • 14,415
  • 11
  • 80
  • 128
  • Where do I override it? How will it help? From where do I call this class? – kittu88 Mar 07 '13 at 06:05
  • inside your activity friend. As inner class. – Gunaseelan Mar 07 '13 at 06:18
  • I am getting an error with the variable names, can you please suggest me a code edit if you do not mind? – kittu88 Mar 07 '13 at 06:21
  • Yes friend. But now i am little busy. can you wait for an hour. – Gunaseelan Mar 07 '13 at 06:26
  • `TextView textView = (TextView) rowView .findViewById(R.id.list_label_name); textView.setText("("+map.get("Id")+") "+map.get("name"));` below this line you can find your editText as this way right friend. In this way any problem friend. – Gunaseelan Mar 07 '13 at 06:30
  • like `EditText et = (EditText) rowView .findViewById(R.id.list_edit_name); ` – Gunaseelan Mar 07 '13 at 06:31
  • I did something like this: http://justpaste.it/24x6 this helped me. But it is only picking up the quantity from the first row. the consecutive ones are not returning any value... – kittu88 Mar 07 '13 at 06:46
0

It will be very simple if you use custom adapter for your listview.

you can see this Custom Adapter for List View

and This one also useful for you how to get EditText value from listview

Community
  • 1
  • 1
Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78