15

I used ListView to dynamic add item,but there is a problem about not Smooth add. there are textView and button in my listActivity,Iwant to Press button ,then TextView's text can auto add to ListView,but i Pressed button, it donot work,unless after i enter content , press "OK"Key ,then Pressed button, TextView's text can auto add to ListView. I donot know why. If I continuous Pressed button, as 3 times, then press "Ok" key, the content

auto add list

View but 3 times.

 public class DynamicListItems extends ListActivity {
   private static final String   ITEM_KEY   = "key";
   ArrayList<HashMap<String, String>>   list= new ArrayList<HashMap<String, String>>();
private SimpleAdapter   adapter;
private EditText    newValue;@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.dynamic_list);
    newValue = (EditText) findViewById(R.id.new_value_field);

    setListAdapter(new SimpleAdapter(this, list, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value }));
    ((ImageButton) findViewById(R.id.button)).setOnClickListener(getBtnClickListener());
}

private OnClickListener getBtnClickListener() {
    return new OnClickListener() {
        public void onClick(View view) {
            try {

                HashMap<String, String> item = new HashMap<String, String>();
                item.put(ITEM_KEY, newValue.getText().toString());
                list.add(item);

                adapter.notifyDataSetChanged();
            } catch (NullPointerException e) {
                Log.i("[Dynamic Items]", "Tried to add null value");
            }
        }
    };
   }}

How to dynamic delete the item ?

  • dynamic_list.xml only contains listView ,button,textView
  • row.xml contains TextView
Siddharth
  • 9,349
  • 16
  • 86
  • 148
pengwang
  • 19,536
  • 34
  • 119
  • 168

4 Answers4

19

notifyDataSetChanged() method is used to update the adapter.

Here I am posting a working answer steps by step.

First of main.xml file :

<?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:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" 
        android:id="@+id/input">

        <EditText
            android:id="@+id/editText_input"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/button_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:text="Add" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_above="@+id/input"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/listView_items"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>

    </LinearLayout>

</RelativeLayout>

Here MainActivity.java :

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
    private EditText etInput;
    private Button btnAdd;
    private ListView lvItem;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dyanamic_list);
        setUpView();

    }

    private void setUpView() {
        etInput = (EditText)this.findViewById(R.id.editText_input);
        btnAdd = (Button)this.findViewById(R.id.button_add);
        lvItem = (ListView)this.findViewById(R.id.listView_items);

        itemArrey = new ArrayList<String>();
        itemArrey.clear();

        itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
        lvItem.setAdapter(itemAdapter);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                addItemList();
            }
        });

        etInput.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    addItemList();
                }
                return true;
            }
        });
    }

    protected void addItemList() {
        if (isInputValid(etInput)) {
            itemArrey.add(0,etInput.getText().toString());
            etInput.setText("");
            itemAdapter.notifyDataSetChanged();
        }   
    }

    protected boolean isInputValid(EditText etInput2) {
        if (etInput2.getText().toString().trim().length()<1) {
            etInput2.setError("Please Enter Item");
            return false;
        } else {
            return true;
        }
    }
}
Tony
  • 5,972
  • 2
  • 39
  • 58
Ashish Dwivedi
  • 8,048
  • 5
  • 58
  • 78
  • 1
    what's `R.layout.simle_list_item_1` ?? – Alan Deep Nov 08 '12 at 16:23
  • 2
    @AlanDeep this is not R.layout.simle_list_item_1, Its android.R.layout.simple_list_item_1 , this statement define the row layout of the list, Here simple_list_item_1 is the xml file of layout which are defined in the android sdk. – Ashish Dwivedi Nov 09 '12 at 10:30
2

Is your getBtnClickListener method part of the ListActivity or ArrayAdapter class?

For me, when I update from the ListActivity class, I use this code...

// code to add a Contact to my database
// code to add a Contact to the list that
//   that is used by the ListView
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);

When I am updating from a method inside the ArrayAdapter class, I use this code...

 // from a LongPress on a ListView item
 convertView.setOnLongClickListener(new OnLongClickListener(){
     @Override
     public boolean onLongClick(View view) {
         view.performHapticFeedback(0, View.HAPTIC_FEEDBACK_ENABLED);
         // code to remove a Contact name from my database
         // code to remove that Contact name from my list
         //    that is used by the ListView
         ContactsAdapter.this.notifyDataSetChanged();
         return true;
     });
Ryan Alford
  • 7,514
  • 6
  • 42
  • 56
  • 1
    thank you for your help, my getBtnClickListener method is part of the ListActivity ,which only a button but not belong to listView. i am not understand your code . my code can work,but I want to konw the reason I must press "oK" Press,then press button,after i enter content over in the textView. i think i donot need press"OK". – pengwang Jan 05 '10 at 05:10
1

I use a thread to add more data to my list in background and then notifydatasetchange, It work successfully

Here are complete code : http://code.google.com/p/dynamic-listview/source/checkout

Tai Tran
  • 1,406
  • 3
  • 15
  • 27
0

Yes!!, the method notifyDataSetChanged() applied in the ArrayAdapter before you fulling him, was the solution for me. Reading from Firebase.

Objects

    private DatabaseReference myRef;
    ArrayList<String> lista;
    ArrayAdapter<String> adapter;

OnCreate

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    myRef = database.getReference("chat");

    //GETTIN MY DATA TO SHOW IN CHAT
    lista = new ArrayList<String>();

OnResume

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnappy : dataSnapshot.getChildren()){
                for (DataSnapshot rePostSnappy : postSnappy.getChildren()){
                    // Defined Array values to show in ListView
                    lista.add(new String(rePostSnappy.getValue().toString()));
                    adapter.notifyDataSetChanged();//Notyfing adapter that will goes to change
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, lista);

    ListView listVista = (ListView) findViewById(R.id.list);
    listVista.setAdapter(adapter);
Mario Alzate
  • 372
  • 3
  • 8