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");
}
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.
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'm a new programmer and new in Android. I'm using this example http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/ and it works great.
Now I want to make the items (Dell, Samsung Galaxy S3, etc) to call a function to open a new activity with different information each.
For example:
If I touch Dell, a new Activity has to show up showing me information about Dell. If I touch Samsung, the same thing.
I Googled but couldn't find anything helpfull, any hint? I think this is basic, but I'm new so I don't really know where to start
In your activity, where you defined your listview
you write
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
in your adapter's getItem you write
public ItemClicked getItem(int position){
return items.get(position);
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), DiscussAddValu.class);
startActivity(i);
}
});
You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.
http://developer.android.com/reference/android/os/Parcelable.html
Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.
Here I launch the kmlreader class of my app when I recieve an onclick in the listview.
Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview
List<KmlSummary> summary = null;
...
public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";
...
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
lastshownitem = position;
Intent intent = new Intent(context, KmlReader.class);
intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
summary.get(position));
startActivity(intent);
}
later in the new activity I pull out the parseable class with
kmlSummary = intent.getExtras().getParcelable(
ImageTextListViewActivity.EXTRA_KMLSUMMARY);
//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.
public KmlSummary(Parcel in) {
this._id = in.readInt();
this._description = in.readString();
this._name = in.readString();
this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
in.readDouble());
this._resrawid = in.readInt();
this._resdrawableid = in.readInt();
this._pathstring = in.readString();
String s = in.readString();
this.set_isThumbCreated(Boolean.parseBoolean(s));
}
#Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeInt(this._id);
arg0.writeString(this._description);
arg0.writeString(this._name);
arg0.writeDouble(this.get_bounds().southwest.latitude);
arg0.writeDouble(this.get_bounds().southwest.longitude);
arg0.writeDouble(this.get_bounds().northeast.latitude);
arg0.writeDouble(this.get_bounds().northeast.longitude);
arg0.writeInt(this._resrawid);
arg0.writeInt(this._resdrawableid);
arg0.writeString(this.get_pathstring());
String s = Boolean.toString(this.isThumbCreated());
arg0.writeString(s);
}
Good Luck
Danny117
You should definitely extend you ArrayListAdapter and implement this in your getView() method. The second parameter (a View) should be inflated if it's value is null, take advantage of it and set it an onClickListener() just after inflating.
Suposing it's called your second getView()'s parameter is called convertView:
convertView.setOnClickListener(new View.OnClickListener() {
public void onClick(final View v) {
if (isSamsung) {
final Intent intent = new Intent(this, SamsungInfo.class);
startActivity(intent);
}
else if (...) {
...
}
}
}
If you want some info on how to extend ArrayListAdapter, I recommend this link.
well in your onitemClick you will send the selected value like deal , and send it in your intent when opening new activity and in your new activity get the sent data and related to selected item will display your data
to get the name from the list
String item = yourData.get(position).getName();
to set data in intent
intent.putExtra("Key", item);
to get the data in second activity
getIntent().getExtras().getString("Key")
for what kind of Hell implementing Parcelable ?
he is passing to adapter String[] so
get item(String) at position
create intent
put it as extra
start activity
in activity get extra
to store product list you can use here HashMap
(for example as STATIC object)
example class describing product:
public class Product {
private String _name;
private String _description;
private int _id
public Product(String name, String description,int id) {
_name = name;
_desctription = description;
_id = id;
}
public String getName() {
return _name;
}
public String getDescription() {
return _description;
}
}
Product dell = new Product("dell","this is dell",1);
HashMap<String,Product> _hashMap = new HashMap<>();
_hashMap.put(dell.getName(),dell);
then u pass to adapter set of keys as:
String[] productNames = _hashMap.keySet().toArray(new String[_hashMap.size()]);
when in adapter u return view u set listener like this for example:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Context context = parent.getContext();
String itemName = getItem(position)
someView.setOnClikListener(new MyOnClickListener(context, itemName));
}
private class MyOnClickListener implements View.OnClickListener {
private String _itemName;
private Context _context
public MyOnClickListener(Context context, String itemName) {
_context = context;
_itemName = itemName;
}
#Override
public void onClick(View view) {
//------listener onClick example method body ------
Intent intent = new Intent(_context, SomeClassToHandleData.class);
intent.putExtra(key_to_product_name,_itemName);
_context.startActivity(intent);
}
}
then in other activity:
#Override
public void onCreate(Bundle) {
String productName = getIntent().getExtra(key_to_product_name);
Product product = _hashMap.get(productName);
}
*key_to_product_name is a public static String to serve as key for extra
ps. sorry for typo i was in hurry :)
ps2. this shoud give you a idea how to do it
ps3. when i will have more time i I'll add a detailed description
MY COMMENT:
DO NOT USE ANY SWITCH STATEMENT
DO NOT CREATE SEPARATE ACTIVITIES FOR EACH PRODUCT ( U NEED ONLY ONE)
listview.setOnItemClickListener(new OnItemClickListener(){
//setting onclick to items in the listview.
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Intent intent;
switch(position){
// case 0 is the first item in the listView.
case 0:
intent = new Intent(Activity.this,firstActivity.class);
break;
//case 1 is the second item in the listView.
case 1:
intent = new Intent(Activity.this,secondActivity.class);
break;
case 2:
intent = new Intent(Activity.this,thirdActivity.class);
break;
//add more if you have more items in listView
startActivity(intent);
}
});
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Intent intent;
switch(position){
case 0:
intent = new Intent(Activity.this,firstActivity.class);
break;
case 1:
intent = new Intent(Activity.this,secondActivity.class);
break;
case 2:
intent = new Intent(Activity.this,thirdActivity.class);
break;
//add more if you have more items in listview
//0 is the first item 1 second and so on...
}
startActivity(intent);
}
});
I was able to go around the whole thing by replacing the context reference from this or Context.this to getapplicationcontext.
Right. I have an action that needs to call another activity. As I understand this, I need to use Intents to do so if I want to parse values to this activity.
However, my code fails and im a little lost as to why.
My main activity:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
/*Menu item: String name, String menu ID*/
/*ToDo: Logic to fecth new menu structure from server*/
menuItem MI1 = new menuItem("menu item 1","1");
menuItem MI2 = new menuItem("menu item 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new menuAdapter(this, AMI));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
//Toast.makeText(Runner.this, AMI.get(position).getMenuID(), Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(v.getContext(), showMenu.class);
myIntent.putExtra("parentID", AMI.get(position).getMenuID());
startActivityForResult(myIntent, 0);
}
});
The "Toast" works just fine, however when I call the showMenu class it crashes.
The showMenu class looks as follows:
public class showMenu extends Activity{
public String menuParent = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.submenu);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
menuParent = extras.getString("parentID");
}
/*ToDo: Logic to fecth new menu structure from server*/
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
menuItem MI1 = new menuItem("submenu 1","1");
menuItem MI2 = new menuItem("submenu 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new subMenuAdapter(this, AMI));
}
public class subMenuAdapter extends BaseAdapter {
private ArrayList<menuItem> MIL = new ArrayList<menuItem>();
public static final int ACTIVITY_CREATE = 10;
public subMenuAdapter(Context c, ArrayList<menuItem> AMI) {
MIL = AMI;
}
public int getCount() {
return MIL.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
v = (LinearLayout) li.inflate(R.layout.grid_item, null);
TextView tv = (TextView)v.findViewById(R.id.grid_text);
tv.setText(MIL.get(position).getMenuname());
} else {
v = convertView;
}
return v;
}
}
}
Any idea why it crashes?
I think you have to register your Intent in your AndroidManifest.xml
<activity
android:name="Package.Name.showMenu"
android:theme="#android:style/Theme.Light"></activity>
As both activities are from same application, there are some other ways as well to pass data between instead of intents. check the link below:
http://developer.android.com/resources/faq/framework.html#3
If you want to use only intents, can you please specify the error you are facing, so that someone can reply you correctly.
if you want to parse values to another activity,you must use startActivityForResult.This is called sub_activity.