Android- Adding subrows to a ListView! - android

ive been attempting to add subrows to a listview. I have a taxi app which at present shows a list of taxi company names, i want to be able to add some sub rows in which show address, postcode etc.
I have had some attempts at this but none have been successful. I am calling my strings from an array in the strings.xml file. My code at the moment is :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You Have Selected: "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), Booking.class);
intent.putExtra("booking", taxi[selectedPosition]);
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
If anyone can help me get round this problem it would be very much appreciated.
The original question i asked is here: Android - Adding Subitem to a listview
Thanks

Whoops, just noticed this one. I'll paste my edited answer into here:
Okay, just for kicks, I threw this together. It compiles and functions correctly, see if you can adapt it for your particular needs:
layout/taxi_list_item.xml
<?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="100dp"
android:padding="10dp"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_name"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taxi_address"
/>
</LinearLayout>
layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
TaxiMain.java
package com.test.taxi;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TaxiMain extends ListActivity {
/** Called when the activity is first created.
* #return */
class Taxi {
private String taxiName;
private String taxiAddress;
public String getName() {
return taxiName;
}
public void setName(String name) {
taxiName = name;
}
public String getAddress() {
return taxiAddress;
}
public void setAddress(String address) {
taxiAddress = address;
}
public Taxi(String name, String address) {
taxiName = name;
taxiAddress = address;
}
}
public class TaxiAdapter extends ArrayAdapter<Taxi> {
private ArrayList<Taxi> items;
private TaxiViewHolder taxiHolder;
private class TaxiViewHolder {
TextView name;
TextView address;
}
public TaxiAdapter(Context context, int tvResId, ArrayList<Taxi> items) {
super(context, tvResId, items);
this.items = items;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.taxi_list_item, null);
taxiHolder = new TaxiViewHolder();
taxiHolder.name = (TextView)v.findViewById(R.id.taxi_name);
taxiHolder.address = (TextView)v.findViewById(R.id.taxi_address);
v.setTag(taxiHolder);
} else taxiHolder = (TaxiViewHolder)v.getTag();
Taxi taxi = items.get(pos);
if (taxi != null) {
taxiHolder.name.setText(taxi.getName());
taxiHolder.address.setText(taxi.getAddress());
}
return v;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] taxiNames = getResources().getStringArray(R.array.taxi_name_array);
String[] taxiAddresses = getResources().getStringArray(R.array.taxi_address_array);
ArrayList<Taxi> taxiList = new ArrayList<Taxi>();
for (int i = 0; i < taxiNames.length; i++) {
taxiList.add(new Taxi(taxiNames[i], taxiAddresses[i]));
}
setListAdapter(new TaxiAdapter(this, R.layout.taxi_list_item, taxiList));
}
}

Related

listview with imageview in Android Studio

I am new with Android Studio, and I would like to try a listview with pictures on the left shown below. I managed to make such a list with a simple list item, but when I changed the simple item list with an ActivityList, it does not work anymore.
How can I change the ArrayList to combine imageviews with the names? I think it could be possible by using a new class which contains the imageview and name instead of strings.
Code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView friendsListView = findViewById(R.id.friendListView);
final ArrayList<String> myFriends = new ArrayList<String>(asList("Mark","Jane","Sussy","Jan"));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.activity_list_item
, myFriends);
friendsListView.setAdapter(arrayAdapter);
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Hello " + myFriends.get(i), Toast.LENGTH_LONG).show();
}
});
}
}
You're right, you need to create a model class for your list item; this model class contains things that differ from item to item; for instance in your shared picture, a list item has a typical of a picture and a title; and so your model class.
Next, instead of having ArrayList<String>, use ArrayList<Item>; where Item is the model class
Third, you need to create a custom adapter that extends from ArrayAdapter<Item>; that is because you can't use the built-in list item layout "android.R.layout.activity_list_item", because it just offers you with a single string; and now you need to accompany a picture with it.
Below is a simple demo
Model class (Item.java)
class Item {
private int mPicture;
private String mTitle;
int getPicture() {
return mPicture;
}
Item(int picture, String title) {
mPicture = picture;
mTitle = title;
}
String getTitle() {
return mTitle;
}
}
List View Adapter (ListViewAdapter.java)
public class ListViewAdapter extends ArrayAdapter<Item> {
ListViewAdapter(#NonNull Context context, ArrayList<Item> items) {
super(context, 0, items);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null) {
listItem = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
// Get the {#link Word} object located at this position in the list
Item currentItem = getItem(position);
ImageView picture = listItem.findViewById(R.id.IvPicture);
picture.setBackgroundResource(currentItem.getPicture());
TextView title = listItem.findViewById(R.id.tvTitle);
title.setText(currentItem.getTitle());
return listItem;
}
}
Activity class
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.item1, "Item1"));
items.add(new Item(R.drawable.item2, "Item2"));
items.add(new Item(R.drawable.item3, "Item3"));
ListViewAdapter adapter = new ListViewAdapter(this, items);
ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
Activity Layout (activity_main.xml)
<?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">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
List item layout (list_item.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/IvPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item" />
</LinearLayout>
You have to have 3 images into res/drawable named item1, item2, and item3
Hope this satisfies your need.
activity_main.xml
<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=".MainActivity"
android:background="#color/grey_300"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
</RelativeLayout>
cards_layout.xml code:
<android.support.v7.widget.CardView
android:id="#+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#color/color_white"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/imageView"
android:tag="image_tag"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:src="#drawable/ic_launcher"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_weight="2"
android:orientation="vertical"
>
<TextView
android:id="#+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Android Name"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="#+id/textViewVersion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Android Version"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
menu_main.xml code:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item android:id="#+id/add_item"
android:title="Add"
android:orderInCategory="100"
app:showAsAction="always"/>
</menu>
MainActivity.java
package com.journaldev.recyclerviewcardview;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<DataModel> data;
static View.OnClickListener myOnClickListener;
private static ArrayList<Integer> removedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<DataModel>();
for (int i = 0; i < MyData.nameArray.length; i++) {
data.add(new DataModel(
MyData.nameArray[i],
MyData.versionArray[i],
MyData.id_[i],
MyData.drawableArray[i]
));
}
removedItems = new ArrayList<Integer>();
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
}
private static class MyOnClickListener implements View.OnClickListener {
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
removeItem(v);
}
private void removeItem(View v) {
int selectedItemPosition = recyclerView.getChildPosition(v);
RecyclerView.ViewHolder viewHolder
= recyclerView.findViewHolderForPosition(selectedItemPosition);
TextView textViewName
= (TextView) viewHolder.itemView.findViewById(R.id.textViewName);
String selectedName = (String) textViewName.getText();
int selectedItemId = -1;
for (int i = 0; i < MyData.nameArray.length; i++) {
if (selectedName.equals(MyData.nameArray[i])) {
selectedItemId = MyData.id_[i];
}
}
removedItems.add(selectedItemId);
data.remove(selectedItemPosition);
adapter.notifyItemRemoved(selectedItemPosition);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_item) {
//check if any items to add
if (removedItems.size() != 0) {
addRemovedItemToList();
} else {
Toast.makeText(this, "Nothing to add", Toast.LENGTH_SHORT).show();
}
}
return true;
}
private void addRemovedItemToList() {
int addItemAtListPosition = 3;
data.add(addItemAtListPosition, new DataModel(
MyData.nameArray[removedItems.get(0)],
MyData.versionArray[removedItems.get(0)],
MyData.id_[removedItems.get(0)],
MyData.drawableArray[removedItems.get(0)]
));
adapter.notifyItemInserted(addItemAtListPosition);
removedItems.remove(0);
}
}
CustomAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private ArrayList<DataModel> dataSet;
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewName;
TextView textViewVersion;
ImageView imageViewIcon;
public MyViewHolder(View itemView) {
super(itemView);
this.textViewName = (TextView) itemView.findViewById(R.id.textViewName);
this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public CustomAdapter(ArrayList<DataModel> data) {
this.dataSet = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_layout, parent, false);
view.setOnClickListener(MainActivity.myOnClickListener);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {
TextView textViewName = holder.textViewName;
TextView textViewVersion = holder.textViewVersion;
ImageView imageView = holder.imageViewIcon;
textViewName.setText(dataSet.get(listPosition).getName());
textViewVersion.setText(dataSet.get(listPosition).getVersion());
imageView.setImageResource(dataSet.get(listPosition).getImage());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
DataModel.java
public class DataModel {
String name;
String version;
int id_;
int image;
public DataModel(String name, String version, int id_, int image) {
this.name = name;
this.version = version;
this.id_ = id_;
this.image=image;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public int getImage() {
return image;
}
public int getId() {
return id_;
}
}
MyData.java
public class MyData {
static String[] nameArray = {"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich","JellyBean", "Kitkat", "Lollipop", "Marshmallow"};
static String[] versionArray = {"1.5", "1.6", "2.0-2.1", "2.2-2.2.3", "2.3-2.3.7", "3.0-3.2.6", "4.0-4.0.4", "4.1-4.3.1", "4.4-4.4.4", "5.0-5.1.1","6.0-6.0.1"};
static Integer[] drawableArray = {R.drawable.cupcake, R.drawable.donut, R.drawable.eclair,
R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.ics,
R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop,R.drawable.marsh};
static Integer[] id_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView friendsListView = findViewById(R.id.friendListView);
final ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.abc, "Item1"));
items.add(new Item(R.drawable.def, "Item2"));
ListViewAdapter adapter = new ListViewAdapter(this, items);
ListView.setAdapter(adapter);
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Hello " + items.get(i), Toast.LENGTH_LONG).show();
}
});
}
}

I am new in android,i want to delete a row on clicking delete button that are shown in front of each row in list view

This is may XML class random values in which we make a row that I want to delete
randomvalues.xml
<LinearLayout
android:id="#+id/linear"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/addbtn">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/img1"
/>
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/adress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageButton
android:id="#+id/removebtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/remove"/>
</LinearLayout>
</LinearLayout>
this is my activity_main XML in which i used a list view to show a row that I make in random values XML file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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.example.chaqeel.taskviews.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear">
<ImageButton
android:id="#+id/addbtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/add"
android:layout_marginLeft="280dp"/>
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linear"
>
</ListView>
</RelativeLayout>
This is MainActivity.java in which we used a array to show the values
MainActivity.java
package com.example.chaqeel.taskviews;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.img1, R.drawable.img2, R.drawable.img3,
R.drawable.img4, R.drawable.img5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new dataListAdapter(Names, Address, Images));
}
class dataListAdapter extends BaseAdapter {
String[] Name, Addres;
int[] imge;
/*dataListAdapter() {
Name = null;
Addres = null;
imge=null;
}*/
public dataListAdapter(String[] text, String[] text1, int[] text3) {
Name = text;
Addres = text1;
imge = text3;
}
public int getCount() {
return Name.length;
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomvalues, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(Names[position]);
Addres.setText(Address[position]);
imge.setImageResource(Images[position]);
final ArrayList<String> lvv= new ArrayList<>();
Collections.addAll(lvv,Names);
// Collection.addAll(lvv,Address);
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
lvv.remove(Names);
lvv.remove(Address);
notifyDataSetChanged();
}
});
return (row);
}
}
}
In the onClickListener try the following code
youradapter.notifyDataSetChanged();
In the deletebutton onClickListener try this
Names = ArrayUtils.removeElement(Names,Names[position]);
Address = ArrayUtils.removeElement(Address,Address[position]);
notifyDataSetChanged();
Though it is advised to use OOP concept like a class to hold the Arrays of Names,Address and Images.
Try below code:
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Name = ArrayUtils.removeElement(Names, Names[position]);
Address = ArrayUtils.removeElement(Address, Address[position]);
imge = ArrayUtils.removeElement(imge, imge[position]);
notifyDataSetChanged();
}
});
change this:
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setTag(position);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer index = (Integer) view.getTag();
lvv.remove(index.intValue());
notifyDataSetChanged();
}
});
Are you from Chakwal? I am Chakwalian. Again StackOverflow is telling me that my answer does not meet thier quality requirements.
You need to better idea to use Model class as below:-
create a model class MyModel.class
import java.util.ArrayList;
import java.util.List;
public class MyModel {
String Name, Address;
int image;
public MyModel(String name, String address, int image) {
Name = name;
Address = address;
this.image = image;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
public int getImage() {
return image;
}
}
and then add with adapter class see below:
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.ic_menu_camera, R.drawable.ic_menu_gallery, R.drawable.ic_menu_manage,
R.drawable.ic_menu_send, R.drawable.ic_menu_share};
private List<MyModel> myModel=new ArrayList<>();
private DataListAdapter dataListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
lv = (ListView) findViewById(R.id.listview);
for(int i=0;i<Names.length;i++){
myModel.add( new MyModel(Names[i],Address[i],Images[i]));
}
dataListAdapter=new DataListAdapter(myModel);
lv.setAdapter(dataListAdapter);
}
class DataListAdapter extends BaseAdapter {
private List<MyModel> myModel=new ArrayList<>();
public DataListAdapter(List<MyModel> myModel) {
this.myModel=myModel;
}
public int getCount() {
return myModel.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomevalue, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(myModel.get(position).getName());
Addres.setText(myModel.get(position).getAddress());
imge.setImageResource(myModel.get(position).getImage());
ImageButton dltbutton = (ImageButton) row.findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myModel.remove(position);
notifyDataSetChanged();
}
});
return (row);
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
add android:onClick="addMore" to your add button
it will fine Happy Coding :)
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info =(AdapterContextMenuInfo) item.getMenuInfo();
pos=info.position;
deleteditem=myList.get(pos);
if(item.getTitle()=="Delete")
{
String delete = myList.get(pos);
File f = new File(path + "/"+ delete);
if (f != null && f.exists())
{
f.delete();
}
myList.remove(pos);
adapter. notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "item has deleted",Toast.LENGTH_LONG).show();
}

ListView by an ArrayList of serializable objects

Now I have a serializable Object Class called Tasks, I intend to make a Listview, each object represent an item within the list but when I run the code it does not work
this is the Main Activity :
public class MainActivity extends ActionBarActivity {
EditText NameET, ImportanceED, dateED, TimeED;
String Name, Importance, date, Time;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NameET = (EditText) findViewById(R.id.NameeditText);
ImportanceED = (EditText) findViewById(R.id.ImportanceeditText2);
dateED = (EditText) findViewById(R.id.dateeditText3);
TimeED = (EditText) findViewById(R.id.timeeditText4);
public void GetTexts() {
Name = NameET.getText().toString();
Importance = ImportanceED.getText().toString();
date = dateED.getText().toString();
Time = TimeED.getText().toString();
}
public void AddTask(View view) {
String testName = NameET.getText().toString().trim();
String testImportance = ImportanceED.getText().toString().trim();
String testDate = dateED.getText().toString().trim();
String testTime = TimeED.getText().toString().trim();
GetTexts();
OpenDetailsActivity();
}
}
public void OpenDetailsActivity() {
Intent DetailsIntent = new Intent(this, DetailsActivity.class);
DetailsIntent.putExtra("Name",Name );
DetailsIntent.putExtra("Importance",Importance );
DetailsIntent.putExtra("date",date );
DetailsIntent.putExtra("Time",Time );
startActivity(DetailsIntent);
}
and this is the List containing activity :
public class DetailsActivity extends Activity {
ListView list;
String Name;
String Importance;
String date;
String Time ;
ArrayList <Tasks>TaskList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_list);
Intent intent = getIntent();
Name= intent.getStringExtra("Name");
Importance= intent.getStringExtra("Importance");
date= intent.getStringExtra("date");
Time= intent.getStringExtra("Time");
addToList();
}
public void addToList() {
int i ;
int N = TaskList.size();
if (N > 0 ){
i = N + 1 ;
} else {
i= 0 ;
}
Everything works fine untill here , the list appears blank
TaskList.add(i, new Tasks(Name, Importance, date, Time));
ListAdapter adapter = new ListAdapter(this, TaskList);
list = (ListView) findViewById(R.id.listView_tasks);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String SelectedTask = TaskList.get(position).getName();
Toast.makeText(getApplicationContext(), SelectedTask, Toast.LENGTH_SHORT).show();
this is Tasks Serializable class
class Tasks implements Serializable {
String name="";
String date="";
String time = "";
String importance="";
public Tasks(String name, String importance, String date , String time) {
this.date = date;
this.importance = importance;
this.name = name;
this.time = time;
}
public String getDate() {
return date;
}
public String getImportance() {
return importance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTime() {
return time;
}
and this is the custom adapter
public class ListAdapter extends ArrayAdapter {
private final Activity context;
List<Tasks> TaskList;
public ListAdapter(Activity context, List<Tasks> TaskList) {
super(context, R.layout.row_layout);
this.context=context;
this.TaskList=TaskList;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.row_layout, null , false);
TextView Name = (TextView) rowView.findViewById(R.id.NameTV);
TextView Date = (TextView) rowView.findViewById(R.id.dateTV);
TextView Importance = (TextView) rowView.findViewById(R.id.importanceTV);
TextView Time = (TextView) rowView.findViewById(R.id.timeTV);
TaskList.get(position).getName();
Name.setText(TaskList.get(position).getName());
Date.setText(TaskList.get(position).getDate());
Importance.setText(TaskList.get(position).getImportance());
Time.setText(TaskList.get(position).getTime());
return rowView;
this is task_list Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView_tasks" />
</LinearLayout>
and this row_layout
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/NameTV"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/importanceTV" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/dateTV" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/timeTV" />
</LinearLayout>
</LinearLayout>
I have do some changes in your code, I tested it on my pc and it is working.
I only update ListAdapter.java and It works.
ListAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Usman Asghar on 23/02/2016.
*/
public class ListAdapter extends ArrayAdapter {
Context context;
List<Tasks> TaskList;
public ListAdapter(Activity context, List<Tasks> TaskList) {
super(context, R.layout.row_layout,TaskList);
this.context = context;
this.TaskList = TaskList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, null, false);
}
TextView Name = (TextView) view.findViewById(R.id.NameTV);
TextView Date = (TextView) view.findViewById(R.id.dateTV);
TextView Importance = (TextView) view.findViewById(R.id.importanceTV);
TextView Time = (TextView) view.findViewById(R.id.timeTV);
Name.setText(TaskList.get(position).getName());
Date.setText(TaskList.get(position).getDate());
Importance.setText(TaskList.get(position).getImportance());
Time.setText(TaskList.get(position).getTime());
return view;
}
}
I changed ArrayAdapter constructor to
super(context, R.layout.row_layout);
That
super(context, R.layout.row_layout,TaskList);
ArrayAdapter does not work until we do not specify what data we want to show on ListView.
And I Do some little Changes in getView() method.
Add to your adapter this method:
#Override
public int getCount() {
return TaskList.size();
}
Change this:
TaskList.add(i, new Tasks(Name, Importance, date, Time));
to this:
TaskList.add(new Tasks(Name, Importance, date, Time));

Android: CustomListView with CustomAdapter, Call Button is not working

In my app I have 3 views
ImagiveView
TextView
Button
ImagView displays image accordingly, TextView and Button display names and number accordingly. But the problem is when I click on the button it does not call to the number which is displaying on the button. Although it does open the android caller app.
Telephone numbers are in string.xml file.
Here I provide my all files. Please help me
strings.xml
<string-array name="names">
<item>Abdul Malik</item>
<item>Adeel ur Rehman</item>
<item>Asad Majeeb</item>
<item>Ata ul Salam</item>
<item>Atta ul Qadir</item>
<item>Bilal Scunder</item>
<item>Chaudry Adnan Ahmed</item>
<item>Chaudry Imran</item>
<item>Ejaz Ahmed Saroya</item>
<item>Hamid Joya</item>
</string-array>
<string-array name="telephones">
<item>0000000000</item>
<item>0486607636</item>
<item>0485256515</item>
<item>0485128196</item>
<item>0465922084</item>
<item>0487150005</item>
<item>0488627993</item>
<item>0484783792</item>
<item>0484688663</item>
<item>0497697050</item>
</string-array>
MainActivity.xml
package com.example.android.listview_with_custom_layout;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
ListView listView;
int [] movie_poster_resource={
R.drawable.movie_1,
R.drawable.movie_2,
R.drawable.movie_3,
R.drawable.movie_4,
R.drawable.movie_5,
R.drawable.movie_6,
R.drawable.movie_7,
R.drawable.movie_8,
R.drawable.movie_9,
R.drawable.movie_10,
};
String [] names ={};
String [] telephones ={};
MoviesAdapter moviesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.list_view);
telephones =getResources().getStringArray(R.array.telephones);
names =getResources().getStringArray(R.array.names);
int i=0;
moviesAdapter= new MoviesAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(moviesAdapter);
for(String titles: names){
MovieDataProvider movieDataProvider= new MovieDataProvider(movie_poster_resource[i], titles, telephones[i]);
moviesAdapter.add(movieDataProvider);
i++;
}
}
}
MoviesDataAdapter
package com.example.android.listview_with_custom_layout;
/**
* Created by temp on 2/11/2015.
*/
public class MovieDataProvider {
private int movie_poster_resource;
private String movie_title;
private String telePhone;
public MovieDataProvider(int movie_poster_resource, String movie_title, String telePhone) {
this.setMovie_poster_resource(movie_poster_resource);
this.setMovie_title(movie_title);
this.telePhone = telePhone;
}
public int getMovie_poster_resource() {
return movie_poster_resource;
}
public String getMovie_title() {
return movie_title;
}
public String getTelePhone() {
return telePhone;
}
public void setMovie_poster_resource(int movie_poster_resource) {
this.movie_poster_resource = movie_poster_resource;
}
public void setMovie_title(String movie_title) {
this.movie_title = movie_title;
}
public void setTelePhone(String telePhone) {
this.telePhone = telePhone;
}
}
MoviesAdapter
package com.example.android.listview_with_custom_layout;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by temp on 2/11/2015.
*/
public class MoviesAdapter extends ArrayAdapter {
List list = new ArrayList();
MovieDataProvider dataProvider;
public MoviesAdapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler {
ImageView Poster;
TextView title;
Button telePhone;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row_layout, parent, false);
handler = new DataHandler();
handler.Poster = (ImageView) row.findViewById(R.id.movie_poster);
handler.title = (TextView) row.findViewById(R.id.movie_title);
handler.telePhone = (Button) row.findViewById(R.id.btn_call);
row.setTag(handler);
} else {
handler = (DataHandler) row.getTag();
}
dataProvider = (MovieDataProvider) this.getItem(position);
handler.Poster.setImageResource(dataProvider.getMovie_poster_resource());
handler.title.setText(dataProvider.getMovie_title());
handler.telePhone.setText(dataProvider.getTelePhone());
handler.telePhone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Intent to launch phone dialer
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + dataProvider.getTelePhone()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
});
return row;
}
}
activity_main.xml
<LinearLayout 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:background="#ffffd953"
tools:context=".MainActivity">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
row_layout.xml
<?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="80dp"
android:background="#000000"
android:orientation="vertical"
android:paddingTop="10dp">
<ImageView
android:id="#+id/movie_poster"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:src="#drawable/movie_1" />
<TextView
android:id="#+id/movie_title"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_toRightOf="#+id/movie_poster"
android:gravity="center"
android:text="This is movie name"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/btn_call"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/movie_title"
android:gravity="center"
android:text="call"
android:textColor="#FFFF" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="#+id/movie_poster"
android:background="#FFFF"></View>
</RelativeLayout>
you forgot to initialize the telephones string in your MainActivity, do same as you did for movie_poster_resource after this it should work, and dont forgot to add permission
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
and last you can update the button click code with
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+dataProvider.getTelePhone()));
startActivity(callIntent);
and update your AdapterClass with this
public class MoviesAdapter extends ArrayAdapter {
List list = new ArrayList();
public MoviesAdapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler {
ImageView Poster;
TextView title;
Button telePhone;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
View row;
row = convertView;
final MovieDataProvider dataProvider = (MovieDataProvider) this.getItem(position);;
DataHandler handler;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row_layout, parent, false);
handler = new DataHandler();
handler.Poster = (ImageView) row.findViewById(R.id.movie_poster);
handler.title = (TextView) row.findViewById(R.id.movie_title);
handler.telePhone = (Button) row.findViewById(R.id.btn_call);
} else {
handler = (DataHandler) row.getTag();
}
handler.Poster.setImageResource(dataProvider.getMovie_poster_resource());
handler.title.setText(dataProvider.getMovie_title());
handler.telePhone.setText(dataProvider.getTelePhone());
handler.telePhone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + dataProvider.getTelePhone()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
});
row.setTag(handler);
return row;
}
}

Inflate ListView with TreeMap data (Custom Adapter)

Solved: I have created an adapter based on #JJV 's suggestion. I am aware that there is plenty of room for improvement, but it works for now.
I have updated this simplified version of my program, with the working code; I hope it will be useful to others:
MainActivity.java:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.Map;
import java.util.TreeMap;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Map<Integer, Object> m = new TreeMap<Integer, Object>();
int key = 123;
Item obj1 = new Item("abc", "xyz", 888);
m.put(key, obj1);
key = 456;
Item obj2 = new Item("def", "zyx", 999);
m.put(key, obj2);
ListAdapter adapter = new TreeMapAdapter(this, (TreeMap<Integer, Object>) m);
ListView itemListView = (ListView) findViewById(R.id.itemListView);
itemListView.setAdapter(adapter);
}
public class Item {
private String name;
private String thing;
private int number;
Item(String name, String thing, int number) {
this.name = name;
this.thing = thing;
this.number = number;
}
public String getName() {
return this.name;
}
public String getThing() {
return this.thing;
}
public int getNumber() {
return this.number;
}
}
}
main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemListView" />
</LinearLayout>
listview_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/thing" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/number" />
</LinearLayout>
TreeMapAdapter.java:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.TreeMap;
public class TreeMapAdapter extends ArrayAdapter<String> {
private Context context;
private TreeMap<Integer, Object> treeMap;
private Integer[] mapKeys;
public TreeMapAdapter(Context context, TreeMap<Integer, Object> data) {
super(context, R.layout.listview_row);
this.context = context;
this.treeMap = data;
mapKeys = treeMap.keySet().toArray(new Integer[getCount()]);
}
public int getCount() {
return treeMap.size();
}
public String getItem(int position) {
return String.valueOf(treeMap.get(mapKeys[position]));
}
public long getItemId(int position) {
return mapKeys[position];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater deviceInflater = LayoutInflater.from(getContext());
View listViewRow = deviceInflater.inflate(R.layout.listview_row, parent, false);
MainActivity.Item test = (MainActivity.Item) treeMap.get(mapKeys[position]);
String nameString = test.getName() + ", ";
String thingString = test.getThing() + ", ";
String numberInt = String.valueOf(test.getNumber());
TextView name = (TextView) listViewRow.findViewById(R.id.name);
TextView thing = (TextView) listViewRow.findViewById(R.id.thing);
TextView number = (TextView) listViewRow.findViewById(R.id.number);
name.setText(nameString);
thing.setText(thingString);
number.setText(numberInt);
return listViewRow;
}
}
Result:
I cannot embed a screenshot of the result in this post, because I do not have 10 reputation, but you can see the result of running the code here: http://i.stack.imgur.com/QoXX1.png
do something like this:
public class TreeMapAdapter extends ArrayAdapter<String> {
private Context context
private TreeMap<Integer, Object> treeMap;
private int mapKeys[];
public TreeMapAdapter(Context context,TreeMap<Integer, Object> treeMap)
this.context=context;
this.treeMao=treeMap;
mapKeys=treemap.keySet().toArray();
}
public int getCount() {
return treeMap.size();
}
public String getItem(int position) {
return treeMap.get(mapKeys[position]);
}
public long getItemId(int position) {
return mapKeys[position];
}
//your getView method....
}

Categories

Resources