listView dynamic add item
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;
}
}
}
Add New Item in Listview dynamically
Illusionist, I've felt your pain as a beginner and have struggled with these exercises myself. The above advice from MH regarding using a list and adding straight to the adapter is correct. I've included an altered version of the exercise, but it basically does what you want it to do. I've added a couple of buttons, one to add a new item to the list and one to exit the application. Both have "onClick" added in the xml layout file for the main activity.
See if you can follow what I've done and let me know if you have any questions or concerns...
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
public class MainActivity extends ListActivity {
EditText et;
String listItem[]={"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText);
List values = new ArrayList();
for (int i = 0; i < listItem.length; i++) {
values.add(listItem[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
public void onClick(View view) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
String device;
switch (view.getId()) {
case R.id.addItem:
List myList = new ArrayList();
device = et.getText().toString();
myList.add(device);
adapter.add(device);
et.setText("");
break;
case R.id.exit:
finish();
break;
}
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
The associated xml layout file looks like...
<?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" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/addItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Item"
android:onClick="onClick"/>
<Button
android:id="@+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bye Bye"
android:onClick="onClick"/>
</LinearLayout>
<EditText
android:id="@+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Text Goes Here"/>
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Note: be careful of the ListView id; it has to be the way you see it above when using ListActivity... http://www.vogella.com/articles/AndroidListView/article.html
Dynamically Add Items to ListView
Trying to use this class instead of ListViewItem class that posted :
public class ListViewItem extends RelativeLayout {
@SuppressWarnings("deprecation")
public ListViewItem(Context context) {
super(context);
this.M_speedTextView = new TextView(context);
this.M_nameTextView = new TextView(context);
this.M_progressBar = new ProgressBar(context, null,
android.R.attr.progressBarStyleHorizontal);
this.M_activityButton = new Button(context);
this.M_speedTextView.setId(new Random().nextInt());
this.M_nameTextView.setId(new Random().nextInt());
this.M_progressBar.setId(new Random().nextInt());
this.M_activityButton.setId(new Random().nextInt());
this.setId(new Random().nextInt());
/***************************************************************/
this.setLayoutParams(new AbsListView.LayoutParams(
LayoutParams.FILL_PARENT, 50));
this.setBackgroundResource(android.R.color.transparent);
// Name Text setting
LayoutParams nameTextParams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
nameTextParams.setMargins(5, 10, 0, 0);
nameTextParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 1);
nameTextParams.addRule(RelativeLayout.LEFT_OF,
this.M_speedTextView.getId());
this.M_nameTextView.setTextSize(15);
this.M_nameTextView.setText("TextView");
this.M_nameTextView.setSingleLine();
this.M_nameTextView.setEllipsize(TruncateAt.END);
this.addView(this.M_nameTextView, nameTextParams);
// Activity Button setting
LayoutParams activityParams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
activityParams.setMargins(0, 5, 5, 0);
activityParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1);
activityParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 1);
this.M_activityButton.setText("Start");
this.addView(this.M_activityButton, activityParams);
// ProgressBar setting
LayoutParams progressParams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
progressParams.addRule(RelativeLayout.ALIGN_BOTTOM,
this.M_activityButton.getId());
progressParams.addRule(RelativeLayout.ALIGN_LEFT,
this.M_nameTextView.getId());
progressParams.addRule(RelativeLayout.BELOW,
this.M_nameTextView.getId());
progressParams.addRule(RelativeLayout.LEFT_OF,
this.M_activityButton.getId());
this.addView(this.M_progressBar, progressParams);
// Speed TextView setting
LayoutParams speedParam = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
speedParam.addRule(RelativeLayout.ALIGN_BASELINE,
this.M_nameTextView.getId());
speedParam.addRule(RelativeLayout.ALIGN_BOTTOM,
this.M_nameTextView.getId());
speedParam.addRule(RelativeLayout.LEFT_OF,
this.M_activityButton.getId());
this.M_speedTextView.setText("0 KiB/s");
this.M_speedTextView.setTextSize(15);
this.addView(this.M_speedTextView, speedParam);
}
public void setSpeed(int speed) {
this.M_speedTextView.setText(Integer.toString(speed));
}
public void setName(String name) {
this.M_nameTextView.setText(name);
}
public void setProgress(int progress) {
this.M_progressBar.setProgress(progress);
}
public void setButtonText(String text) {
this.M_activityButton.setText(text);
}
TextView M_speedTextView;
TextView M_nameTextView;
ProgressBar M_progressBar;
Button M_activityButton;
}
and in getView
method of adapter :
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return this.M_items.get(position);
}
Dynamically add items in list view
For this Just use the example given below:
For Instance you are Adding Some Strings into your List
So Create a ListArray like this
ArrayList<String> listItems = new ArrayList<String>();
now whenever you want to add certain string into list just do this thing
EditText editText = (EditText) findViewById(R.id.edit);
listItems.add("my string"); OR
listItems.add(editText.getText.toString()); //incase if you are getting string value from editText and adding it into the list
Use this Xml inside your linear layout in main.xml
<EditText android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Now when you have added one item dynamically then call this
adapter.notifyDataSetChanged();
The above will update your list and display the upadted list.
For more info about this see the following links:
http://www.androidpeople.com/android-custom-listview-tutorial-part-1
http://www.androidpeople.com/android-custom-listview-tutorial-part-2
http://www.androidpeople.com/android-custom-dynamic-listview-%E2%80%93part3
In these tutorials you can replace String[] with ArrayList as given at the top of the answer ook and when you want to add any item just simply use the second code snippet.
Thanks
sHaH
Dynamically add items to list view using custom adapter for Android app
- In your adapter change the
Locations data[]
from array toArrayList<Location>
and override the appropriate constructor - In your activity, make your variable
data
a field (typeArrayList<Location>
) - When you add a location you can use
data.add(location)
- Then you can call
notifyDatasetChanged()
on your adapter
Example code.
dynamically add elements on list view
You did it very well! And yes, there is a solution. The key method is adapter.notifyDataSetChanged(); if you call this notifyDataSetChanged the adapter will try to "redraw" the ListView, so if you make any change in the data source (In this case you will add an element to the list) you will see a different number of cells.
So you need to follow these steps:
1- Replace the String[] for a List
2- Keep a reference to the adapter created
3- Call notifyDataSetChanged() on this adapter every time you make a change (This method should be called in the UI thread)
The final code should look something like this:
final GridView gridView = (GridView) getActivity().findViewById(R.id.gv);
final RoomsBtnAdapter adapter = new RoomsBtnAdapter(getContext(), strings, colors);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
strings.add("New String");
adapter.notifyDataSetChanged(); //This is the key ingredient
case 1:
}
}
});
How to add items to listview dynamically
Your first issue is because of the way Java handles mutable data types. Since the resultsMap
is a global variable, when you call put()
with the same key value (i.e. "idForID"
and "idForAmount"
) you are overriding the last input for those keys. The reference listItems
has still points to the resultsMap
object that now contains the overridden data, leaving you with multiple copies of the same object.
A simple solution to this problem would be to move the declaration of the resultsMap
object inside of your addItem()
function (making it a local variable). Though I would also advise against this solution, considering the unnecessary added complexity of a Map
nested inside of a List
.
Instead, a solution that would also solve your second issue would be to create a class to contain the data.
final class Product(String id, String amount) {
public final String id;
public final String amount;
public Product(String id, String amount) {
this.id = id;
this.amount = amount;
}
/**
* Override equals() and hashCode() as well.
* These can be generated in Android Studio by selecting
* Code > Generate… > equals() and hashCode().
*/
}
Then use this object as the type for your list and adapter, instead of Map<String, String>
, and make sure you create a new object each time you add an item to the list. This will allow you to create a List
containing any amount of items, even if they have the same id
.
As @Raza suggested, I would also recommend switching from a ListView
to a RecyclerView
. As stated in the ArrayAdapter
documentation.
Note: If you are considering using array adapter with a ListView, consider using RecyclerView instead. RecyclerView offers similar
features with better performance and more flexibility than ListView
provides. See the Recycler View guide.
Related Topics
How to Remove All Debug Logging Calls Before Building the Release Version of an Android App
Get Screen Width and Height in Android
Different Values Folders in Android
Dilemma: When to Use Fragments VS Activities:
How to Prevent Custom Views from Losing State Across Screen Orientation Changes
How to Update a Single Row in a Listview
How to Use the Animation Framework Inside the Canvas
Set Style For Textview Programmatically
How to Detect Orientation Change in Layout in Android
How to Pass Images (Bitmaps) Between Android Activities Using Bundles
Getapplication() Vs. Getapplicationcontext()
How to Assign an Id to a View Programmatically
How to Exit from the Application and Show the Home Screen
How to Transfer Some Data to Another Fragment
How to Change an Application Icon Programmatically in Android
How to Create a Custom-Shaped Bitmap Marker With Android Map API V2
Saving and Reading Bitmaps/Images from Internal Memory in Android