Listview Dynamic Add Item

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

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

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 list view using custom adapter for Android app

  1. In your adapter change the Locations data[] from array to
    ArrayList<Location> and override the appropriate constructor
  2. In your activity, make your variable data a field (type ArrayList<Location>)
  3. When you add a location you can use data.add(location)
  4. Then you can call notifyDatasetChanged() on your adapter

Example code.

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

Append items dynamically to ListView

Calling setState is the correct way of triggering an UI update.

From the docs:

Calling setState notifies the framework that the internal state of
this object has changed in a way that might impact the user interface
in this subtree, which causes the framework to schedule a build for
this State object.

If you just change the state directly without calling setState, the
framework might not schedule a build and the user interface for this
subtree might not be updated to reflect the new state.

Here is a small example of a ListView with a Button that appends items to it.

import 'package:flutter/material.dart';

void main() => runApp(new MaterialApp(home: MyList()));

class MyList extends StatefulWidget {
@override
_MyListState createState() => _MyListState();
}

class _MyListState extends State<MyList> {
int value = 2;

_addItem() {
setState(() {
value = value + 1;
});
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("MyApp"),
),
body: ListView.builder(
itemCount: this.value,
itemBuilder: (context, index) => this._buildRow(index)),
floatingActionButton: FloatingActionButton(
onPressed: _addItem,
child: Icon(Icons.add),
),
);
}

_buildRow(int index) {
return Text("Item " + index.toString());
}
}

Java dynamically add items to a listview

First of all, you need to put your ListView in an accessible place, so that you can find the reference again later. Thus, do not declare it as a local variable, but as a field.

Then, to add an item, you simply do:

listview.getItems().add("some new element");

How to add items dynamically to a custom adapter for ListView

The problem is that your adapter's lfs's field and your activity's elements field both refer to the same List instance. This happens because you pass elements to the ListAdapter constructor, and then simply assign this.lfs = lfs.

So let's look at what happens when you pass elements to updateItems()...

public void updateItems(List<Lf> lfs) {
this.lfs.clear(); // this.lfs and the input lfs are the same list, so this clears both
this.lfs.addAll(lfs); // input lfs is now empty, so addAll() does nothing
this.notifyDataSetChanged();
}

Probably the best thing to do is to create a copy of the list in your adapter's constructor.

this.lfs = new ArrayList<>(lfs);

Now your adapter and activity will reference different lists, so this.lfs.clear() won't accidentally clear out the very list you're passing to it.

Flutter adding items dynamically to ListView in Stateless Widget

So as far from your code i have created an example for you please check the example

MainPage:

import 'package:demo_stack/search_page.dart';
import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('List app'),
actions: [
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SearchPage()));
},
icon: const Icon(Icons.six__ft_apart_rounded))
],
),
);
}
}

Search widget.

import 'package:flutter/material.dart';

class SearchPage extends StatefulWidget {
const SearchPage({Key? key}) : super(key: key);

@override
State<SearchPage> createState() => _SearchPageState();
}

// Using the statefull widget to change the index of tab bars
class _SearchPageState extends State<SearchPage> {
var tabIndex = 0;

@override
Widget build(BuildContext context) {
var childList = [
const FirstPage(),
Container(color: Colors.red),
Container(color: Colors.yellow),
Container(color: Colors.cyan),
];

return Scaffold(
body: DefaultTabController(
length: 4,
initialIndex: tabIndex,
child: Scaffold(
appBar: AppBar(),
body: childList[tabIndex],
bottomNavigationBar: TabBar(
onTap: (index) {
setState(() {
tabIndex = index;
});
},
labelColor: Colors.black,
tabs: const <Widget>[
Tab(text: 'First Page'),
Tab(text: 'Red'),
Tab(text: 'Yellow'),
Tab(text: 'Cyan'),
],
),
),
),
);
;
}
}

class FirstPage extends StatelessWidget {
const FirstPage({Key? key}) : super(key: key);

Future<List<Item>> getItems() async {
await Future.delayed(const Duration(seconds: 3));

return [Item("one"), Item("two"), Item("three")];
}

@override
Widget build(BuildContext context) {
return FutureBuilder<List<Item>>(
future: getItems(),
builder: (BuildContext context, snapshot) {

//This is to check currently in which state the app is
// there are four states none,waiting,active,done
// you can add the check accordingly

print(snapshot.connectionState);

return snapshot.data == null
? const Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
var item = snapshot.data![index];
return Padding(
padding: const EdgeInsets.all(15.0),
child: Text(item.name),
);
});
});
}
}

class Item {
final String name;

Item(this.name);
}

This is the search page

If you still face any issue then check the futurebuilder states and add checks accordinly it will work.

Thanks.



Related Topics



Leave a reply



Submit