How can I use the properties of a custom object in a Listview. If I implement an ArrayAdapter with a list of Strings it displays fine in Listview but when I use a list of custom objects, it just outputs the memory address.
The code I have up to now:
ArrayList<CustomObject> allObjects = new ArrayList<>();
allObjects.add("title", "http://url.com"));
ArrayAdapter<NewsObject> adapter = new ArrayAdapter<NewsObject>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, allNews);
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Uri uri = Uri.parse( "http://www.google.com" );
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
There is a similar question here but that is not what I need since I just need to have the title show in list view and when they click extract the url.
An ArrayAdapter displays the value returned by the toString() method, so you will need to override this method in your custom Object class to return the desired String. You will also need to have at least a getter method for the URL, so you can retrieve that in the click event.
public class NewsObject {
private String title;
private String url;
public NewsObject(String title, String url) {
this.title = title;
this.url = url;
}
public String getUrl() {
return url;
}
#Override
public String toString() {
return title;
}
...
}
In the onItemClick() method, position will be the index in the ArrayList of your custom Objects corresponding to the list item clicked. Retrieve the URL, parse it, and call startActivity().
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsObject item = allNews.get(position);
String url = item.getUrl();
Uri uri = Uri.parse(url);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
Please note, I assumed your custom class is NewsObject, as that is what's used with your Adapter example.
If you want to use a methods of your custom class you need to implement a custor ArrayAdapter class... How to create this?
First step
Get your project and create a new class. Then extends class with ArrayAdapter<YourObject>{} and declare inside your atributes that you needs... My example:
public class Room_Adapter extends ArrayAdapter<Room_Object> {
//Declaration of Atributes
private ArrayList<Room_Object> Rooms_Array;
private final Activity context;
private final ListView lvBuinding;
Second
Declare a constructor for this class, always you need an Activity and ArrayList, put inside the others if you need... In my case I needs the listview... My example:
public Room_Adapter(Activity context, ArrayList<Room_Object> Rooms_Array,ListView lvBuinding) {
super(context, R.layout.room_layout, Rooms_Array);
this.context = context;
this.Rooms_Array = Rooms_Array;
this.lvBuinding = lvBuinding;
}
The super method nees your activity, custom layout (if you have it) and your array.
Third
Declare a static class or create a new one if you have a custom row layout. My example have a static class:
public static class Room_View{
//Declaration of Atributes
TextView RoomName;
ImageView RoomState;
TextView NoTroubles;
Button btnRoomRow;
ImageButton btnShowRoomTasks;
ImageButton btnAddTasks;
RelativeLayout RowLayout;
}
Fourth
Override method getView.
#Override
public View getView(int position, View ConvertView, ViewGroup parent) {
//Declaration of Variables
Room_View rowView; //Custom static class with controls
LayoutInflater inflator = context.getLayoutInflater();
if (ConvertView == null) {
rowView = new Room_View();
ConvertView = inflator.inflate(R.layout.room_layout,null,true); //Inflate your view with your custom view.
rowView.RoomName = (TextView) ConvertView.findViewById(R.id.txtvRoom);
rowView.RoomState = (ImageView) ConvertView.findViewById(R.id.ivRoomState);
rowView.NoTroubles = (TextView) ConvertView.findViewById(R.id.txtvNoTroubles);
rowView.btnRoomRow = (Button) ConvertView.findViewById(R.id.btnRoomRow);
rowView.btnAddTasks = (ImageButton) ConvertView.findViewById(R.id.btnAddTask);
rowView.btnShowRoomTasks = (ImageButton) ConvertView.findViewById(R.id.btnShowRoomTasks);
rowView.RowLayout = (RelativeLayout) ConvertView.findViewById(R.id.rowLayout);
ConvertView.setTag(rowView);
}
else
{
rowView = (Room_View) ConvertView.getTag();
}
//Here custom your control stats
Room_Object Room = Rooms_Array.get(position);
rowView.RoomName.setText(Room.getRoomName());
rowView.NoTroubles.setVisibility(View.INVISIBLE);
rowView.btnShowRoomTasks.setClickable(true);
rowView.btnShowRoomTasks.setImageResource(R.drawable.list_3a4b66_50);
rowView.btnShowRoomTasks.setOnClickListener(OnShowTasksClickListener);
//This is for add ClickListiner in my buttons...
rowView.btnAddTasks.setOnClickListener(OnAddTasksClickListener);
rowView.btnRoomRow.setOnClickListener(OnAddTasksClickListener);
if(Room.getStatus().equals("Checked")){
rowView.RowLayout.setBackgroundColor(0xFFC7E6C7);
rowView.btnShowRoomTasks.setClickable(false);
rowView.btnShowRoomTasks.setImageResource(R.drawable.list_999999_50);
rowView.RoomState.setImageResource(R.drawable.check_3ebf4b_50);
}
else if(Room.getStatus().equals("Blocked")){
rowView.RowLayout.setBackgroundColor(0xFFDBC3E5);
rowView.RoomState.setImageResource(R.drawable.key_9330e0_50);
}
else if(Room.getStatus().equals("Dirty")){
rowView.RowLayout.setBackgroundColor(0xfffceedb);
rowView.RoomState.setImageResource(R.drawable.icon_housekeeping_3_yellow);
}
else if(Room.getStatus().equals("Troubled")){
rowView.RowLayout.setBackgroundColor(0xFFF4CECD);
rowView.RoomState.setImageResource(R.drawable.wrench_eb3232_50);
rowView.NoTroubles.setVisibility(View.VISIBLE);
try {
rowView.NoTroubles.setText(Integer.toString(Room.getNoTasks()));
}
catch (Exception ex){
Log.e("-- Error --",ex.getMessage());
}
}
//
//Pay attention *************************************************
//
//Now if you needs to use your custom external class this is the site, now imagine that you need gets string from your custom class in the text view, then:
//Declare class
CustomClass object = new CustomClass();
rowView.(CUSTOM CONTROL FROM YOUR STATIC CLASS).(METHOD OF CONTROL)(object.(CUSTOM METHOD OF YOUR OBJECT));
//For example If you follows my sample then:
rowView.NoTroubles.setText(object.getNumberOfTroubles().toString);
return ConvertView;
}
//Listener Methods for my button controls
private View.OnClickListener OnShowTasksClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
int totalRooms = lvBuinding.getCount() - 1;
int actualRoom = totalRooms - positionSelected;
try{
//Your code;
}
catch (Exception ex){
Log.e("-- CustomError --", ex.getMessage());
}
}
};
private View.OnClickListener OnAddTasksClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
int totalRooms = lvBuinding.getCount() - 1;
int actualRoom = totalRooms - positionSelected;
try{
//Your code;
}
catch (Exception ex){
Log.e("-- CustomError --", ex.getMessage());
}
}
};
}
I think this is that you needs, if you need more info or same advice me and I try to helps you... Good luck, Eduardo!
#mike Answer can be short. ArrayAdapter<Item> Item class should override toString()
#Override
public String toString() {
return name;
}
and you done
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomObject obj = allObjects.get(position);
//Now use obj to access the property
Uri uri = Uri.parse( "http://www.google.com" );
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
You need to override the getView of your Adaptor to display the individual object at a position into your view.
Related
How can I use the properties of a custom object in a Listview. If I implement an ArrayAdapter with a list of Strings it displays fine in Listview but when I use a list of custom objects, it just outputs the memory address.
The code I have up to now:
ArrayList<CustomObject> allObjects = new ArrayList<>();
allObjects.add("title", "http://url.com"));
ArrayAdapter<NewsObject> adapter = new ArrayAdapter<NewsObject>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, allNews);
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Uri uri = Uri.parse( "http://www.google.com" );
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
There is a similar question here but that is not what I need since I just need to have the title show in list view and when they click extract the url.
An ArrayAdapter displays the value returned by the toString() method, so you will need to override this method in your custom Object class to return the desired String. You will also need to have at least a getter method for the URL, so you can retrieve that in the click event.
public class NewsObject {
private String title;
private String url;
public NewsObject(String title, String url) {
this.title = title;
this.url = url;
}
public String getUrl() {
return url;
}
#Override
public String toString() {
return title;
}
...
}
In the onItemClick() method, position will be the index in the ArrayList of your custom Objects corresponding to the list item clicked. Retrieve the URL, parse it, and call startActivity().
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsObject item = allNews.get(position);
String url = item.getUrl();
Uri uri = Uri.parse(url);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
Please note, I assumed your custom class is NewsObject, as that is what's used with your Adapter example.
If you want to use a methods of your custom class you need to implement a custor ArrayAdapter class... How to create this?
First step
Get your project and create a new class. Then extends class with ArrayAdapter<YourObject>{} and declare inside your atributes that you needs... My example:
public class Room_Adapter extends ArrayAdapter<Room_Object> {
//Declaration of Atributes
private ArrayList<Room_Object> Rooms_Array;
private final Activity context;
private final ListView lvBuinding;
Second
Declare a constructor for this class, always you need an Activity and ArrayList, put inside the others if you need... In my case I needs the listview... My example:
public Room_Adapter(Activity context, ArrayList<Room_Object> Rooms_Array,ListView lvBuinding) {
super(context, R.layout.room_layout, Rooms_Array);
this.context = context;
this.Rooms_Array = Rooms_Array;
this.lvBuinding = lvBuinding;
}
The super method nees your activity, custom layout (if you have it) and your array.
Third
Declare a static class or create a new one if you have a custom row layout. My example have a static class:
public static class Room_View{
//Declaration of Atributes
TextView RoomName;
ImageView RoomState;
TextView NoTroubles;
Button btnRoomRow;
ImageButton btnShowRoomTasks;
ImageButton btnAddTasks;
RelativeLayout RowLayout;
}
Fourth
Override method getView.
#Override
public View getView(int position, View ConvertView, ViewGroup parent) {
//Declaration of Variables
Room_View rowView; //Custom static class with controls
LayoutInflater inflator = context.getLayoutInflater();
if (ConvertView == null) {
rowView = new Room_View();
ConvertView = inflator.inflate(R.layout.room_layout,null,true); //Inflate your view with your custom view.
rowView.RoomName = (TextView) ConvertView.findViewById(R.id.txtvRoom);
rowView.RoomState = (ImageView) ConvertView.findViewById(R.id.ivRoomState);
rowView.NoTroubles = (TextView) ConvertView.findViewById(R.id.txtvNoTroubles);
rowView.btnRoomRow = (Button) ConvertView.findViewById(R.id.btnRoomRow);
rowView.btnAddTasks = (ImageButton) ConvertView.findViewById(R.id.btnAddTask);
rowView.btnShowRoomTasks = (ImageButton) ConvertView.findViewById(R.id.btnShowRoomTasks);
rowView.RowLayout = (RelativeLayout) ConvertView.findViewById(R.id.rowLayout);
ConvertView.setTag(rowView);
}
else
{
rowView = (Room_View) ConvertView.getTag();
}
//Here custom your control stats
Room_Object Room = Rooms_Array.get(position);
rowView.RoomName.setText(Room.getRoomName());
rowView.NoTroubles.setVisibility(View.INVISIBLE);
rowView.btnShowRoomTasks.setClickable(true);
rowView.btnShowRoomTasks.setImageResource(R.drawable.list_3a4b66_50);
rowView.btnShowRoomTasks.setOnClickListener(OnShowTasksClickListener);
//This is for add ClickListiner in my buttons...
rowView.btnAddTasks.setOnClickListener(OnAddTasksClickListener);
rowView.btnRoomRow.setOnClickListener(OnAddTasksClickListener);
if(Room.getStatus().equals("Checked")){
rowView.RowLayout.setBackgroundColor(0xFFC7E6C7);
rowView.btnShowRoomTasks.setClickable(false);
rowView.btnShowRoomTasks.setImageResource(R.drawable.list_999999_50);
rowView.RoomState.setImageResource(R.drawable.check_3ebf4b_50);
}
else if(Room.getStatus().equals("Blocked")){
rowView.RowLayout.setBackgroundColor(0xFFDBC3E5);
rowView.RoomState.setImageResource(R.drawable.key_9330e0_50);
}
else if(Room.getStatus().equals("Dirty")){
rowView.RowLayout.setBackgroundColor(0xfffceedb);
rowView.RoomState.setImageResource(R.drawable.icon_housekeeping_3_yellow);
}
else if(Room.getStatus().equals("Troubled")){
rowView.RowLayout.setBackgroundColor(0xFFF4CECD);
rowView.RoomState.setImageResource(R.drawable.wrench_eb3232_50);
rowView.NoTroubles.setVisibility(View.VISIBLE);
try {
rowView.NoTroubles.setText(Integer.toString(Room.getNoTasks()));
}
catch (Exception ex){
Log.e("-- Error --",ex.getMessage());
}
}
//
//Pay attention *************************************************
//
//Now if you needs to use your custom external class this is the site, now imagine that you need gets string from your custom class in the text view, then:
//Declare class
CustomClass object = new CustomClass();
rowView.(CUSTOM CONTROL FROM YOUR STATIC CLASS).(METHOD OF CONTROL)(object.(CUSTOM METHOD OF YOUR OBJECT));
//For example If you follows my sample then:
rowView.NoTroubles.setText(object.getNumberOfTroubles().toString);
return ConvertView;
}
//Listener Methods for my button controls
private View.OnClickListener OnShowTasksClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
int totalRooms = lvBuinding.getCount() - 1;
int actualRoom = totalRooms - positionSelected;
try{
//Your code;
}
catch (Exception ex){
Log.e("-- CustomError --", ex.getMessage());
}
}
};
private View.OnClickListener OnAddTasksClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
int totalRooms = lvBuinding.getCount() - 1;
int actualRoom = totalRooms - positionSelected;
try{
//Your code;
}
catch (Exception ex){
Log.e("-- CustomError --", ex.getMessage());
}
}
};
}
I think this is that you needs, if you need more info or same advice me and I try to helps you... Good luck, Eduardo!
#mike Answer can be short. ArrayAdapter<Item> Item class should override toString()
#Override
public String toString() {
return name;
}
and you done
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomObject obj = allObjects.get(position);
//Now use obj to access the property
Uri uri = Uri.parse( "http://www.google.com" );
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
You need to override the getView of your Adaptor to display the individual object at a position into your view.
How can I use the properties of a custom object in a Listview. If I implement an ArrayAdapter with a list of Strings it displays fine in Listview but when I use a list of custom objects, it just outputs the memory address.
The code I have up to now:
ArrayList<CustomObject> allObjects = new ArrayList<>();
allObjects.add("title", "http://url.com"));
ArrayAdapter<NewsObject> adapter = new ArrayAdapter<NewsObject>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, allNews);
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Uri uri = Uri.parse( "http://www.google.com" );
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
There is a similar question here but that is not what I need since I just need to have the title show in list view and when they click extract the url.
An ArrayAdapter displays the value returned by the toString() method, so you will need to override this method in your custom Object class to return the desired String. You will also need to have at least a getter method for the URL, so you can retrieve that in the click event.
public class NewsObject {
private String title;
private String url;
public NewsObject(String title, String url) {
this.title = title;
this.url = url;
}
public String getUrl() {
return url;
}
#Override
public String toString() {
return title;
}
...
}
In the onItemClick() method, position will be the index in the ArrayList of your custom Objects corresponding to the list item clicked. Retrieve the URL, parse it, and call startActivity().
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsObject item = allNews.get(position);
String url = item.getUrl();
Uri uri = Uri.parse(url);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
Please note, I assumed your custom class is NewsObject, as that is what's used with your Adapter example.
If you want to use a methods of your custom class you need to implement a custor ArrayAdapter class... How to create this?
First step
Get your project and create a new class. Then extends class with ArrayAdapter<YourObject>{} and declare inside your atributes that you needs... My example:
public class Room_Adapter extends ArrayAdapter<Room_Object> {
//Declaration of Atributes
private ArrayList<Room_Object> Rooms_Array;
private final Activity context;
private final ListView lvBuinding;
Second
Declare a constructor for this class, always you need an Activity and ArrayList, put inside the others if you need... In my case I needs the listview... My example:
public Room_Adapter(Activity context, ArrayList<Room_Object> Rooms_Array,ListView lvBuinding) {
super(context, R.layout.room_layout, Rooms_Array);
this.context = context;
this.Rooms_Array = Rooms_Array;
this.lvBuinding = lvBuinding;
}
The super method nees your activity, custom layout (if you have it) and your array.
Third
Declare a static class or create a new one if you have a custom row layout. My example have a static class:
public static class Room_View{
//Declaration of Atributes
TextView RoomName;
ImageView RoomState;
TextView NoTroubles;
Button btnRoomRow;
ImageButton btnShowRoomTasks;
ImageButton btnAddTasks;
RelativeLayout RowLayout;
}
Fourth
Override method getView.
#Override
public View getView(int position, View ConvertView, ViewGroup parent) {
//Declaration of Variables
Room_View rowView; //Custom static class with controls
LayoutInflater inflator = context.getLayoutInflater();
if (ConvertView == null) {
rowView = new Room_View();
ConvertView = inflator.inflate(R.layout.room_layout,null,true); //Inflate your view with your custom view.
rowView.RoomName = (TextView) ConvertView.findViewById(R.id.txtvRoom);
rowView.RoomState = (ImageView) ConvertView.findViewById(R.id.ivRoomState);
rowView.NoTroubles = (TextView) ConvertView.findViewById(R.id.txtvNoTroubles);
rowView.btnRoomRow = (Button) ConvertView.findViewById(R.id.btnRoomRow);
rowView.btnAddTasks = (ImageButton) ConvertView.findViewById(R.id.btnAddTask);
rowView.btnShowRoomTasks = (ImageButton) ConvertView.findViewById(R.id.btnShowRoomTasks);
rowView.RowLayout = (RelativeLayout) ConvertView.findViewById(R.id.rowLayout);
ConvertView.setTag(rowView);
}
else
{
rowView = (Room_View) ConvertView.getTag();
}
//Here custom your control stats
Room_Object Room = Rooms_Array.get(position);
rowView.RoomName.setText(Room.getRoomName());
rowView.NoTroubles.setVisibility(View.INVISIBLE);
rowView.btnShowRoomTasks.setClickable(true);
rowView.btnShowRoomTasks.setImageResource(R.drawable.list_3a4b66_50);
rowView.btnShowRoomTasks.setOnClickListener(OnShowTasksClickListener);
//This is for add ClickListiner in my buttons...
rowView.btnAddTasks.setOnClickListener(OnAddTasksClickListener);
rowView.btnRoomRow.setOnClickListener(OnAddTasksClickListener);
if(Room.getStatus().equals("Checked")){
rowView.RowLayout.setBackgroundColor(0xFFC7E6C7);
rowView.btnShowRoomTasks.setClickable(false);
rowView.btnShowRoomTasks.setImageResource(R.drawable.list_999999_50);
rowView.RoomState.setImageResource(R.drawable.check_3ebf4b_50);
}
else if(Room.getStatus().equals("Blocked")){
rowView.RowLayout.setBackgroundColor(0xFFDBC3E5);
rowView.RoomState.setImageResource(R.drawable.key_9330e0_50);
}
else if(Room.getStatus().equals("Dirty")){
rowView.RowLayout.setBackgroundColor(0xfffceedb);
rowView.RoomState.setImageResource(R.drawable.icon_housekeeping_3_yellow);
}
else if(Room.getStatus().equals("Troubled")){
rowView.RowLayout.setBackgroundColor(0xFFF4CECD);
rowView.RoomState.setImageResource(R.drawable.wrench_eb3232_50);
rowView.NoTroubles.setVisibility(View.VISIBLE);
try {
rowView.NoTroubles.setText(Integer.toString(Room.getNoTasks()));
}
catch (Exception ex){
Log.e("-- Error --",ex.getMessage());
}
}
//
//Pay attention *************************************************
//
//Now if you needs to use your custom external class this is the site, now imagine that you need gets string from your custom class in the text view, then:
//Declare class
CustomClass object = new CustomClass();
rowView.(CUSTOM CONTROL FROM YOUR STATIC CLASS).(METHOD OF CONTROL)(object.(CUSTOM METHOD OF YOUR OBJECT));
//For example If you follows my sample then:
rowView.NoTroubles.setText(object.getNumberOfTroubles().toString);
return ConvertView;
}
//Listener Methods for my button controls
private View.OnClickListener OnShowTasksClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
int totalRooms = lvBuinding.getCount() - 1;
int actualRoom = totalRooms - positionSelected;
try{
//Your code;
}
catch (Exception ex){
Log.e("-- CustomError --", ex.getMessage());
}
}
};
private View.OnClickListener OnAddTasksClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
int totalRooms = lvBuinding.getCount() - 1;
int actualRoom = totalRooms - positionSelected;
try{
//Your code;
}
catch (Exception ex){
Log.e("-- CustomError --", ex.getMessage());
}
}
};
}
I think this is that you needs, if you need more info or same advice me and I try to helps you... Good luck, Eduardo!
#mike Answer can be short. ArrayAdapter<Item> Item class should override toString()
#Override
public String toString() {
return name;
}
and you done
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomObject obj = allObjects.get(position);
//Now use obj to access the property
Uri uri = Uri.parse( "http://www.google.com" );
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
You need to override the getView of your Adaptor to display the individual object at a position into your view.
I have an array of objects. In my listview, I pass only the name of those objects but when someone clicks on any of them, I want a new window to pop up and to see the extra information from my items. Can I do that somehow?
This is how my list activity looks like:
public class ListItemsActivity extends ListActivity {
String[] mTestArray;
ListView listView;
private static final String TAG = "ListActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "Trying to create the list activitye");
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter;
mTestArray = getResources().getStringArray(R.array.sections);
ArrayList<Sweet> sweets = getSweets(mTestArray);
ArrayList<String> result = getSweetsNames(mTestArray);
Log.d(TAG, mTestArray.toString());
adapter = new ArrayAdapter<String>(
this,
R.layout.activity_list_items,
result;
setListAdapter(adapter);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
parent.setItemChecked(position, parent.isItemChecked(position));
Toast.makeText(this, "You have selected " + mTestArray[position],
Toast.LENGTH_SHORT).show();
}
So this is ok, it shows me a lsit of names. And when I click on them it jsut tells me on a small popup thing that I've selected it. What I want is actually to open a new window and show all the information from my items. Is that possible? How would I go around to do it?
The only way I found is to do something like this:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position ) {
case 0: Intent newActivity = new Intent(this, i1.class);
startActivity(newActivity);
break;
case 1: Intent newActivity = new Intent(this, i2.class);
startActivity(newActivity);
break;
case 2: Intent newActivity = new Intent(this, i3.class);
startActivity(newActivity);
break;
case 3: Intent newActivity = new Intent(this, i4.class);
startActivity(newActivity);
break;
case 4: Intent newActivity = new Intent(this, i5.class);
startActivity(newActivity);
break;
}
}
But it's a bad approach for these reasons:
1) I have an unknown number of elements
2)I dont have 1000 activities for each item, I want 1 general window that would depend on some integer position.
Can I do it this way?
If you are getting position of the item from listView, then I think you can get the information about same item by the use of Adapter.
Codes that you can try:
Make a xml that your list view items would have:
This can include any types of items and items would be seen in the list view as you would want to show it. I am making an xml named list_items_view.xml and including just a text view in the listview.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/nameInList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="26dp"
android:padding="7dp"/>
</RelativeLayout>
Make a class that would include the items that you want to bind with each list-items:
Here I am binding each list items with it's description, price, and callories (You can change that according to your need), and make constructor and getter-setter method for each one.Name of the class is ListDetailsClass:
public class ListDetailsClass {
String price,name, description,calories;
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public ListDetailsClass(String price, String name, String description, String calories) {
this.price = price;
this.name = name;
this.description = description;
this.calories = calories;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCalories() {
return calories;
}
public void setCalories(String calories) {
this.calories = calories;
}
}
Make an adapter that could adapt the properties of the xml and the class in one single item:
Here I have made an adapter class that extends BaseAdapter and implemented it's methods according to use of my purpose.Name of the class is adapterForLV:
public class adapterForLV extends BaseAdapter {
ArrayList<ListDetailsClass> itemsInList;
Context mContext;
LayoutInflater inflater;
public Context getmContext() {
return mContext;
}
public void setmContext(Context mContext) {
this.mContext = mContext;
}
public ArrayList<ListDetailsClass> getItemsInList() {
return itemsInList;
}
public void setItemsInList(ArrayList<ListDetailsClass> itemsInList) {
this.itemsInList = itemsInList;
}
public adapterForLV(ArrayList<ListDetailsClass> itemsInList, Context mContext) {
this.itemsInList = itemsInList;
this.mContext = mContext;
}
#Override
public int getCount() {
return itemsInList.size();
}
#Override
public Object getItem(int position) {
return itemsInList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(inflater == null){
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView == null){
convertView = inflater.inflate(R.layout.list_items_view,null);
}
TextView nameOfItem = (TextView) convertView.findViewById(R.id.nameInList);
ListDetailsClass items = itemsInList.get(position);
String name = items.getName();
nameOfItem.setText(items.getName());
return convertView;
}
}
Finally implement adapter in your main activity so as to include the list items with bound data:(Name of the activity is MainActivity)
ListView listView;
ArrayList<ListDetailsClass> list = new ArrayList<>();
adapterForLV customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv) ;
//Adapted the list form with customAdapter
customAdapter = new adapterForLV(list,this);
//Set the listview to the customAdapter
listView.setAdapter(customAdapter);
//Made two new objects of the ListDetaisClass to add data in the listview
ListDetailsClass newData = new ListDetailsClass("3$","abc","description","543 cal");
ListDetailsClass newData2 = new ListDetailsClass("35.3$","item name","description about item","callories about it");
//Added data to the list
list.add(newData);
list.add(newData2);
//Listview item click listener implementation
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = customAdapter.getItemsInList().get(position).getName();
String description = customAdapter.getItemsInList().get(position).getDescription();
String price = customAdapter.getItemsInList().get(position).getPrice();
String calories = customAdapter.getItemsInList().get(position).getCalories();
//Intent to pass the data of the list item to next activity
Intent i = new Intent(getApplicationContext(),Main2Activity.class);
i.putExtra("Item_Name",name);
i.putExtra("Item_Desc",description);
i.putExtra("Item_Price",price);
i.putExtra("Item_cal",calories);
startActivity(i);
}
});
}
Getting the data to show in the form according to our use in the new activity:
Here you have to define a new xml for the new activity so that data could be shown in the form we want.
Main2Activity:
//defined textViews to show my data
TextView itemName,itemDescription,itemPrice,itemCal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
itemName = (TextView) findViewById(R.id.ItemName);
itemDescription = (TextView) findViewById(R.id.ItemDescr);
itemCal = (TextView) findViewById(R.id.ItemCal);
itemPrice = (TextView) findViewById(R.id.ItemPrice);
//Getting data from oldActivity i.e. MainActivity
Intent i = getIntent();
//Setting data to textViews
itemName.setText("Name: "+i.getStringExtra("Item_Name"));
itemDescription.setText("Description: "+i.getStringExtra("Item_Desc"));
itemPrice.setText("Price: "+i.getStringExtra("Item_Price"));
itemCal.setText("Calories: "+i.getStringExtra("Item_cal"));
}
Screenshots after implementation:
Listview
Item details in new activity
Hope this help you!
I didn't understand well but you could use Intent for new Window For example:
public void onListItemClick(ListView parent, View v, int position, long id) {
parent.setItemChecked(position, parent.isItemChecked(position));
Intent intent=new Intent(ListItemActivity.this, newDetailActivity.class); //newDetailActivity is a Activity you need to create or can say redirect window
startActivity(intent); // This opens a window
}
Here's Official Documentation for more information Follow Documentation
You can start a common activity and pass the selected item along with the intent :
public void onListItemClick(ListView parent, View v, int position, long id) {
parent.setItemChecked(position, parent.isItemChecked(position));
//DetailsActivity is the activity which shows the extra details
Intent intent=new Intent(ListItemActivity.this, DetailsActivity.class);
//Add the item that the user clicked on, the class has to implement Parcelable or Serializable
intent.putExtra("data", sweets.getItem(position));
startActivity(intent); // This opens a window
}
In the opened activity, you can get the item from the intent and display it's contents :
//in newDetailActivity :
Sweet s = getIntent().getExtras.getParcelable("data");
The easiest way of passing data between activities is using intents.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent newActivity = new Intent(this, i1.class);
newActivity.putExtra("id", postion);
newActivity.putExtra("key", value);
startActivity(newActivity);
}
In short, putExtra method takes a key and value
which can be retrieved in the destination Activity.
Bundle extras = getIntent().getExtras();
String id,key;
if(extras == null) {
id = null;
key = null;
} else {
id= extras.getString("id");
key= extras.getString("key");
}
How can I use the properties of a custom object in a Listview. If I implement an ArrayAdapter with a list of Strings it displays fine in Listview but when I use a list of custom objects, it just outputs the memory address.
The code I have up to now:
ArrayList<CustomObject> allObjects = new ArrayList<>();
allObjects.add("title", "http://url.com"));
ArrayAdapter<NewsObject> adapter = new ArrayAdapter<NewsObject>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, allNews);
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Uri uri = Uri.parse( "http://www.google.com" );
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
There is a similar question here but that is not what I need since I just need to have the title show in list view and when they click extract the url.
An ArrayAdapter displays the value returned by the toString() method, so you will need to override this method in your custom Object class to return the desired String. You will also need to have at least a getter method for the URL, so you can retrieve that in the click event.
public class NewsObject {
private String title;
private String url;
public NewsObject(String title, String url) {
this.title = title;
this.url = url;
}
public String getUrl() {
return url;
}
#Override
public String toString() {
return title;
}
...
}
In the onItemClick() method, position will be the index in the ArrayList of your custom Objects corresponding to the list item clicked. Retrieve the URL, parse it, and call startActivity().
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsObject item = allNews.get(position);
String url = item.getUrl();
Uri uri = Uri.parse(url);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
Please note, I assumed your custom class is NewsObject, as that is what's used with your Adapter example.
If you want to use a methods of your custom class you need to implement a custor ArrayAdapter class... How to create this?
First step
Get your project and create a new class. Then extends class with ArrayAdapter<YourObject>{} and declare inside your atributes that you needs... My example:
public class Room_Adapter extends ArrayAdapter<Room_Object> {
//Declaration of Atributes
private ArrayList<Room_Object> Rooms_Array;
private final Activity context;
private final ListView lvBuinding;
Second
Declare a constructor for this class, always you need an Activity and ArrayList, put inside the others if you need... In my case I needs the listview... My example:
public Room_Adapter(Activity context, ArrayList<Room_Object> Rooms_Array,ListView lvBuinding) {
super(context, R.layout.room_layout, Rooms_Array);
this.context = context;
this.Rooms_Array = Rooms_Array;
this.lvBuinding = lvBuinding;
}
The super method nees your activity, custom layout (if you have it) and your array.
Third
Declare a static class or create a new one if you have a custom row layout. My example have a static class:
public static class Room_View{
//Declaration of Atributes
TextView RoomName;
ImageView RoomState;
TextView NoTroubles;
Button btnRoomRow;
ImageButton btnShowRoomTasks;
ImageButton btnAddTasks;
RelativeLayout RowLayout;
}
Fourth
Override method getView.
#Override
public View getView(int position, View ConvertView, ViewGroup parent) {
//Declaration of Variables
Room_View rowView; //Custom static class with controls
LayoutInflater inflator = context.getLayoutInflater();
if (ConvertView == null) {
rowView = new Room_View();
ConvertView = inflator.inflate(R.layout.room_layout,null,true); //Inflate your view with your custom view.
rowView.RoomName = (TextView) ConvertView.findViewById(R.id.txtvRoom);
rowView.RoomState = (ImageView) ConvertView.findViewById(R.id.ivRoomState);
rowView.NoTroubles = (TextView) ConvertView.findViewById(R.id.txtvNoTroubles);
rowView.btnRoomRow = (Button) ConvertView.findViewById(R.id.btnRoomRow);
rowView.btnAddTasks = (ImageButton) ConvertView.findViewById(R.id.btnAddTask);
rowView.btnShowRoomTasks = (ImageButton) ConvertView.findViewById(R.id.btnShowRoomTasks);
rowView.RowLayout = (RelativeLayout) ConvertView.findViewById(R.id.rowLayout);
ConvertView.setTag(rowView);
}
else
{
rowView = (Room_View) ConvertView.getTag();
}
//Here custom your control stats
Room_Object Room = Rooms_Array.get(position);
rowView.RoomName.setText(Room.getRoomName());
rowView.NoTroubles.setVisibility(View.INVISIBLE);
rowView.btnShowRoomTasks.setClickable(true);
rowView.btnShowRoomTasks.setImageResource(R.drawable.list_3a4b66_50);
rowView.btnShowRoomTasks.setOnClickListener(OnShowTasksClickListener);
//This is for add ClickListiner in my buttons...
rowView.btnAddTasks.setOnClickListener(OnAddTasksClickListener);
rowView.btnRoomRow.setOnClickListener(OnAddTasksClickListener);
if(Room.getStatus().equals("Checked")){
rowView.RowLayout.setBackgroundColor(0xFFC7E6C7);
rowView.btnShowRoomTasks.setClickable(false);
rowView.btnShowRoomTasks.setImageResource(R.drawable.list_999999_50);
rowView.RoomState.setImageResource(R.drawable.check_3ebf4b_50);
}
else if(Room.getStatus().equals("Blocked")){
rowView.RowLayout.setBackgroundColor(0xFFDBC3E5);
rowView.RoomState.setImageResource(R.drawable.key_9330e0_50);
}
else if(Room.getStatus().equals("Dirty")){
rowView.RowLayout.setBackgroundColor(0xfffceedb);
rowView.RoomState.setImageResource(R.drawable.icon_housekeeping_3_yellow);
}
else if(Room.getStatus().equals("Troubled")){
rowView.RowLayout.setBackgroundColor(0xFFF4CECD);
rowView.RoomState.setImageResource(R.drawable.wrench_eb3232_50);
rowView.NoTroubles.setVisibility(View.VISIBLE);
try {
rowView.NoTroubles.setText(Integer.toString(Room.getNoTasks()));
}
catch (Exception ex){
Log.e("-- Error --",ex.getMessage());
}
}
//
//Pay attention *************************************************
//
//Now if you needs to use your custom external class this is the site, now imagine that you need gets string from your custom class in the text view, then:
//Declare class
CustomClass object = new CustomClass();
rowView.(CUSTOM CONTROL FROM YOUR STATIC CLASS).(METHOD OF CONTROL)(object.(CUSTOM METHOD OF YOUR OBJECT));
//For example If you follows my sample then:
rowView.NoTroubles.setText(object.getNumberOfTroubles().toString);
return ConvertView;
}
//Listener Methods for my button controls
private View.OnClickListener OnShowTasksClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
int totalRooms = lvBuinding.getCount() - 1;
int actualRoom = totalRooms - positionSelected;
try{
//Your code;
}
catch (Exception ex){
Log.e("-- CustomError --", ex.getMessage());
}
}
};
private View.OnClickListener OnAddTasksClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int positionSelected = lvBuinding.getPositionForView((View) v.getParent());
int totalRooms = lvBuinding.getCount() - 1;
int actualRoom = totalRooms - positionSelected;
try{
//Your code;
}
catch (Exception ex){
Log.e("-- CustomError --", ex.getMessage());
}
}
};
}
I think this is that you needs, if you need more info or same advice me and I try to helps you... Good luck, Eduardo!
#mike Answer can be short. ArrayAdapter<Item> Item class should override toString()
#Override
public String toString() {
return name;
}
and you done
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomObject obj = allObjects.get(position);
//Now use obj to access the property
Uri uri = Uri.parse( "http://www.google.com" );
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
You need to override the getView of your Adaptor to display the individual object at a position into your view.
ok so i have an array adapted listview (the array adapting is done in another class).. i just got the click listener working for the list but now i want set it up so that when i click an item it pulls the strings from the clicked item and piggybacks them on the intent to a new activity.. i figure im supposed to use intent.putextra however im not sure how to pull the correct strings corresponding to the item that i click on.. my code is below.. im simply lost to be honest
//Initialize the ListView
lstTest = (ListView)findViewById(R.id.lstText);
//Initialize the ArrayList
alrts = new ArrayList<Alerts>();
//Initialize the array adapter notice with the listitems.xml layout
arrayAdapter = new AlertsAdapter(this, R.layout.listitems,alrts);
//Set the above adapter as the adapter for the list
lstTest.setAdapter(arrayAdapter);
//Set the click listener for the list
lstTest.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView adapterView, View view, int item, long arg3) {
Intent intent = new Intent(
HomePageActivity.this,
PromotionActivity.class
);
finish();
startActivity(intent);
}
});
my alerts class..
public class Alerts {
public String cityid;
public String promoterid;
public String promoshortcontent;
public String promocontent;
public String promotitle;
public String locationid;
public String cover;
#Override
public String toString() {
return "City: " +cityid+ " Promoter: " +promoterid+ "Short Promotion: " +promoshortcontent+ "Promotion: " +promocontent+ "Title: " +promotitle+ "Location: " +locationid+ "Cover: " +cover+ "$";
}
}
anddddd my alertsadapter class..
public class AlertsAdapter extends ArrayAdapter<Alerts> {
int resource;
String response;
Context context;
//Initialize adapter
public AlertsAdapter(Context context, int resource, List<Alerts> items) {
super(context, resource, items);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout alertView;
//Get the current alert object
Alerts al = getItem(position);
//Inflate the view
if(convertView==null)
{
alertView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, alertView, true);
}
else
{
alertView = (LinearLayout) convertView;
}
//Get the text boxes from the listitem.xml file
TextView textPromo =(TextView)alertView.findViewById(R.id.txtPromo);
TextView textPromoter =(TextView)alertView.findViewById(R.id.txtPromoter);
TextView textLocation =(TextView)alertView.findViewById(R.id.txtLocation);
//Assign the appropriate data from our alert object above
textPromo.setText(al.promocontent);
textPromoter.setText(al.promoterid);
textLocation.setText(al.locationid);
return alertView;
}
}
You need to use the onItemClick event's parameters
a full more readable param enum with param name is
(AdapterView<?> parent, View view, int pos, long id)
that means you have the pos param that indicated the position in the adapter.
What you have to do is:
jump to pos in the adapter
read out the values from the adapter
use putExtra to signup for the intent
had an epiphany over the weekend about how to fix this problem and i finally found a good work around for my app.. i know it isnt optimal because i hard coded the number 100 into it but for my uses as of now i know i wont ever have that many list items..
i added these 2 bits of code to my alertsadapter class
int startzero = 0;
public static String[][] promomatrix = new String[6][100];
and
promomatrix[0][startzero] = al.cityid;
promomatrix[1][startzero] = al.promoterid;
promomatrix[2][startzero] = al.promocontent;
promomatrix[3][startzero] = al.promotitle;
promomatrix[4][startzero] = al.locationid;
promomatrix[5][startzero] = al.cover;
startzero++;
then went to my homepageactivity class and added this to the click listener
Intent intent = new Intent(
HomePageActivity.this,PromotionActivity.class);
intent.putExtra("listitemcity", AlertsAdapter.promomatrix[0][pos]);
intent.putExtra("listitempromoter", AlertsAdapter.promomatrix[1][pos]);
intent.putExtra("listitemcontent", AlertsAdapter.promomatrix[2][pos]);
intent.putExtra("listitemtitle", AlertsAdapter.promomatrix[3][pos]);
intent.putExtra("listitemlocation", AlertsAdapter.promomatrix[4][pos]);
intent.putExtra("listitemcover", AlertsAdapter.promomatrix[5][pos]);
finish();
startActivity(intent);
and finally went to my promotionactivity (where i was trying to send the strings) and added this
Bundle extras = getIntent().getExtras();
if (extras == null){
return;
}
String listitemcity = extras.getString("listitemcity");
String listitempromoter = extras.getString("listitempromoter");
String listitemcontent = extras.getString("listitemcontent");
String listitemtitle = extras.getString("listitemtitle");
String listitemlocation = extras.getString("listitemlocation");
String listitemcover = extras.getString("listitemcover");
worked like a charm.. i hope this helps someone :)