Changing extended ListView to Custom ListView - android

My MainActivity extends ListActivity, but now I want to add an ActionBar and this Activity should extend ActionBarActivity, to do that I need to change extended ListView to a custom ListView. I've tried many times, but unsuccessful. How can I do it?
Here's part of my MainActivity Code:
public class MainActivity extends ListActivity {
.
.
.
// Hashmap for ListView
ArrayList<HashMap<String, String>> testList;
#Override
protected void onCreate(Bundle savedInstanceState) {
testList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, testList,
R.layout.list_item, new String[] { TAG_NAME, TAG_DESCRICAO }, new int[] { R.id.name,
R.id.descricao });
setListAdapter(adapter);
}
}

Yes, go ahead and extend ActionBarActivity. Then, define your ListView in a layout file. For example, your layout will look something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/lv_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
Now, in your activity, you set the content view to the layout we created above. Next, get a reference to the ListView with findViewById. Finally, bind your adapter to the ListView. By the way, an ArrayAdapter may suit you better.
Code:
public class ListTestActivity extends ActionBarActivity {
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_test);
mListView = (ListView) findViewById(R.id.lv_list);
mListView.setAdapter(new SimpleAdapter(
MainActivity.this, testList,
R.layout.list_item, new String[] { TAG_NAME, TAG_DESCRICAO }, new int[] { R.id.name,
R.id.descricao });
}
}

Try including super.onCreate(savedInstanceState) prior to everything else you have within the onCreate.

Related

Android listview unfortunately, app has stopped

I have an issue about listview filled with string item althouh I look up a search about it. I don't undertand where the problems comes from though I define layout.xml correctly. How can I solve it out?
public class A extends AppCompatActivity {
ArrayList<String> items= null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a);
items = new ArrayList<String>();
items.add("AAAA");
items.add("BBB");
items.add("CCC");
items.add("DDD");
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
ListView listView = (ListView) findViewById(R.id.listviewAttactivePlaces);
listView.setAdapter(itemsAdapter);
}
a.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listviewAttactivePlaces"
tools:context="com.example.android.turkeytourguide.AttactivePlacesActivity">
</ListView>
you have to declare your arrayList as follows
List<String> items = new ArrayList<>();
please add this..
items=new ArrayList<String>();
items.add("AAAA");
items.add("BBB");
items.add("CCC");
items.add("DDD");
Try changing the type in declaration
public class A extends AppCompatActivity {
List<String> items= null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a);
items = new ArrayList<String>();
items.add("AAAA");
items.add("BBB");
items.add("CCC");
items.add("DDD");
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
ListView listView = (ListView) findViewById(R.id.listviewAttactivePlaces);
listView.setAdapter(itemsAdapter);
}

How to add elements to a ListView?

I want to add an element to my ListView. I tried with myAdapter.add() (see code below) since ArrayAdapter has an add() method. But that didn't work. What is the correct way to add elements to my ListView?
public class LinearLayoutDemo extends ListActivity implements OnItemClickListener {
private static final String[] items={"1", "2", "4", "8", "16", "32", "64"};
ListView myLV;
ArrayAdapter myAdapter;
#Override public void onCreate(Bundle icicle) {
super.onCreate(icicle);
myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, items);
myLV = (ListView) findViewById(android.R.id.list);
myLV.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
myLV.setAdapter(myAdapter);
// The following causes the program to fail:
myAdapter.add("128");
}
Also, the program crashes if if I try myAdapter.clear(). Am I not using the ArrayAdapter correctly?
You have to add to items and then call myAdapter.notifyDataSetChanged(). But the way you defined items as final you cannot add. If you want to add new element easily you should declare items as ArrayList<String>.
public class LinearLayoutDemo extends ListActivity implements OnItemClickListener {
private static List<String> items = Arrays.asList("1", "2", "4", "8", "16", "32", "64");
ListView myLV;
ArrayAdapter myAdapter;
#Override public void onCreate(Bundle icicle) {
super.onCreate(icicle);
myAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_activated_1, items);
myLV = (ListView) findViewById(android.R.id.list);
myLV.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
myLV.setAdapter(myAdapter);
items.add("128");
myAdapter.notifyDataSetChanged();
}
You need to call:
myAdapter.notifyDataSetChanged();
on the adapter after adding the elements to notify on any changes in adapter's data set, But you can't change your data set after creation of Array. use ArrayList instead.

ListView update

I have two activities with ListView. This two activitises have individual layout-file. First have myListView01, second have myListView02. How to update listView's adapters?
I do so:
ListView list = (ListView)findViewById(R.id.myListView01);
myAdapter = new ArrayAdapter<String>(this, R.layout.item01, R.id.label, array01);
list.setAdapter(myAdapter);
I remove some items from the array01 and I need to update my listView without this elements.
But this solution to ListActivity does not work:
myAdapter.notifyDataSetChanged();
my code:
package ...;
import ...;
public class Class01 extends Activity
{
ArrayAdapter<String> mAdapter;
ArrayList<String> array01 = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout01);
ListView list = (ListView)findViewById(R.id.my_list01);
mAdapter = new ArrayAdapter<String>(this, R.layout.item01, R.id.label, array01);
list.setAdapter(mAdapter);
}
public void onListItemClick (ListView parent, View v, int position, long id)
{
array01 = deleteElementByPosition(array01, position);
mAdapter.notifyDataSetChanged(); //does not work
}
public void deleteElementByPosition()
{
...
}
}
You have not set onItemClickListener for your ListView.
Extend your Class01 from ListActivity. Activity class doesn't have onListItemClick() method so it is never invoked. Or set your listener with setOnItemClickListener() for your ListView.

How do you dynamically add elements to a ListView on Android?

Can anyone explain or suggest a tutorial to dynamically create a ListView in android?
Here are my requirements:
I should be able to dynamically add new elements by pressing a button.
Should be simple enough to understand (possibly without any performance improvements or convertView, for instance)
I know there are quite a few questions on this topic, but I couldn't find any that answer my question.
Create an XML layout first in your project's res/layout/main.xml folder:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/addBtn"
android:text="Add New Item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="addItems"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>
</LinearLayout>
This is a simple layout with a button on the top and a list view on the bottom. Note that the ListView has the id #android:id/list which defines the default ListView a ListActivity can use.
public class ListViewDemo extends ListActivity {
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter++);
adapter.notifyDataSetChanged();
}
}
android.R.layout.simple_list_item_1 is the default list item layout supplied by Android, and you can use this stock layout for non-complex things.
listItems is a List which holds the data shown in the ListView. All the insertion and removal should be done on listItems; the changes in listItems should be reflected in the view. That's handled by ArrayAdapter<String> adapter, which should be notified using:
adapter.notifyDataSetChanged();
An Adapter is instantiated with 3 parameters: the context, which could be your activity/listactivity; the layout of your individual list item; and lastly, the list, which is the actual data to be displayed in the list.
instead of
listItems.add("New Item");
adapter.notifyDataSetChanged();
you can directly call
adapter.add("New Item");
First, you have to add a ListView, an EditText and a button into your activity_main.xml.
Now, in your ActivityMain:
private EditText editTxt;
private Button btn;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTxt = (EditText) findViewById(R.id.editText);
btn = (Button) findViewById(R.id.button);
list = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<String>();
// Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
// and the array that contains the data
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);
// Here, you set the data in your ListView
list.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// this line adds the data of your EditText and puts in your array
arrayList.add(editTxt.getText().toString());
// next thing you have to do is check if your adapter has changed
adapter.notifyDataSetChanged();
}
});
}
This works for me, I hope I helped you
If you want to have the ListView in an AppCompatActivity instead of ListActivity, you can do the following (Modifying #Shardul's answer):
public class ListViewDemoActivity extends AppCompatActivity {
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
private ListView mListView;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list_view_demo);
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter++);
adapter.notifyDataSetChanged();
}
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
And in you layout instead of using android:id="#android:id/list" you can use android:id="#+id/listDemo"
So now you can have a ListView inside a normal AppCompatActivity.
Code for MainActivity.java file.
public class MainActivity extends Activity {
ListView listview;
Button Addbutton;
EditText GetValue;
String[] ListElements = new String[] {
"Android",
"PHP"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView1);
Addbutton = (Button) findViewById(R.id.button1);
GetValue = (EditText) findViewById(R.id.editText1);
final List < String > ListElementsArrayList = new ArrayList < String >
(Arrays.asList(ListElements));
final ArrayAdapter < String > adapter = new ArrayAdapter < String >
(MainActivity.this, android.R.layout.simple_list_item_1,
ListElementsArrayList);
listview.setAdapter(adapter);
Addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListElementsArrayList.add(GetValue.getText().toString());
adapter.notifyDataSetChanged();
}
});
}
}
Code for activity_main.xml layout file.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.listviewaddelementsdynamically_android_examples
.com.MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="ADD Values to listview" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Add elements listView" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
ScreenShot
The short answer: when you create a ListView you pass it a reference to the data.
Now, whenever this data will be altered, it will affect the list view and thus add the item to it, after you'll call adapter.notifyDataSetChanged();.
If you're using a RecyclerView, update only the last element (if you've added it at the end of the list of objs) to save memory with: mAdapter.notifyItemInserted(mItems.size() - 1);
This is the simple answer how to add datas dynamically in listview android kotlin
class MainActivity : AppCompatActivity(){
var listItems = arrayListOf<String>()
val array = arrayOf("a","b","c","d","e")
var listView: ListView? = null
private lateinit var adapter: listViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.scrollview_layout)
listItems.add("a")
listItems.add("b")
listItems.add("c")
listItems.add("d")
listItems.add("e")
//if you want to add array items to a list you can try this for each loop
for(items in array)
listItems.add(items)
//check the result in console
Log.e("TAG","listItems array: $listItems")
adapter = ListViewAdapter()
adapter.updateList(listItems)
adapter.notifyDataSetChanged()
}
}
//Here is the adapter class
class ListviewAdapter : BaseAdapter(){
private var itemsList = arrayListOf<String>()
override fun getView(position: Int, container: View?, parent: ViewGroup?): View {
var view = container
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
if (view == null)
view = inflater.inflate(R.layout.list_pc_summary, parent, false)
return view
}
override fun getItem(position: Int): Any = itemsList[position]
override fun getItemId(position: Int): Long = position.toLong()
override fun getCount(): Int = itemsList.size
fun updateList(listItems: ArrayList<String>()){
this.itemsList = listItems
notifyDatSetChanged
}
}
//Here I just explained two ways, we can do this many ways.

Create ListView programmatically

Hi I am new in Android. Could anyone tell me pls whats the wrong with the following code:
public class ListApp extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView lText = new TextView(this);
lText.setId(0);
ListView lView = new ListView(this);
String[] lStr = new String[]{"AA","BB", "CC"};
ArrayAdapter lAdap = new ArrayAdapter(this,lText.getId(),lStr);
lView.setAdapter(lAdap);
lView.setFocusableInTouchMode(true);
setContentView(lView);
}
}
here's a solution that does not require you to write any xml layouts. it uses standard android layouts where possible and no inflation is necessary:
Dialog dialog = new Dialog(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Color Mode");
ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
builder.setView(modeList);
dialog = builder.create();
Try this..
Paste the following code in list_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" android:textColor="#ffffff" android:textStyle="bold" android:background="#drawable/border_cell">
</TextView>
Here is the activity class....
public class UsersListActivity extends ListActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = {"listItem 1", "listItem 2", "listItem 3"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
Best practice is to separate view (xml layout) and controller (Activity).
If you dont want this, try to put
setContentView(lView);
at the beginning of onCreate
public class ListApp extends ListActivity
Make a layout XML file with your listview and use findViewById to set it's adapter after first setting the content view to your layout

Categories

Resources