I am feteching data from server using JSON and showing that data in recycler view. But the problem is I may need to add some new data to the server.
Using volley, request will be send to server and recycler view list will be updated. So the problem is I want to open new activity on each recycler view item click. But my recycler view list will increase if I added some new data to the server. So, I can't change layout/start activity based on itemclick postion.
Is there any better way to implement this?
Just like whatsapp, I want to open new activity/fragment on itemclick of recycler view.
This what I tried to do but this is not proper way. Coz I don't know how many item will be present inside recyclerview. Here is my code:
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
}
#Override
public void onClick(View v) {
final Intent intent;
switch (getAdapterPostion()){
case 0:
intent = new Intent(context, FirstActivity.class);
break;
case 1:
intent = new Intent(context, SecondActivity.class);
break;
...
default:
intent = new Intent(context, DefaultActivity.class);
break;
}
context.startActivity(intent);
}
a proper approach is using an interface in your adapter class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Item> items;
private final OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(Item item);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public void bind (final Item item, final OnItemClickListener listener) {
yourclickableView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(item);
}
});
}
}
public MyAdapter(List<Item> items, OnItemClickListener listener) {
...
this.listener = listener;
items = items;
}
and finally:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.bind(items.get(position), listener);
...
}
and whenever using your adapter class:
myAdapter = new MyAdapter (itemsList, new MyAdapter.OnItemClickListener(){
#Override
public void onItemClick(Item item) {
//bluh bluh...
}
});
If you trying to replicate the functionality of WhatsApp pay attention that when you click on an item on a list the app will not open a new Activity, it will open the same Activity sending different data to load the data for that specific user.
...
Intent intent = new Intent(context, Chat.class);
intent.putExtra("EXTRA_USER_ID", userId);
startActivity(intent);
...
On the Chat.class
...
Intent intent = getIntent();
String userId = intent.getStringExtra("EXTRA_USER_ID");
...
Using this user id you can load data for this specific user.
Related
I have a RecyclerView with some images,here i want to open different Activitys by clicking on different images...
So, i think using the switch statement in the onClick of the adapter will solve my problem but i don't know how to add a switch-if statement in a RecyclerView adapter.i am a beginer in android development so i need some help...
myadapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ImageViewHolder> {
#NonNull
private int[] images;
public RecyclerAdapter(int[] images){
this.images =images;
}
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item2,parent,false);
ImageViewHolder imageViewHolder = new ImageViewHolder(view);
return imageViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
int image_id =images[position];
holder.imagess.setImageResource(image_id);
}
#Override
public int getItemCount() {
return images.length;
}
public static class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView imagess;
TextView titless;
public ImageViewHolder(View itemView) {
super(itemView);
imagess = itemView.findViewById(R.id.image);
titless = itemView.findViewById(R.id.title);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Toast.makeText(itemView.getContext(), "DOWNLOAD ANY TORRENT DOWNLOADER AND OPEN", Toast.LENGTH_LONG).show();
}
}}
So what i want is :
I want to open different activities if the user click the cat image,it should open a activity named cats and if the user clicks the dog image it should open a activity named dogs ...
#Override
public void onClick(View v) {
switch(getAdapterPosition()) {
case 0:
Intent intent = new Intent(context, Cat.class);
context.startActivity(intent);
break;
case 1: // Open second activity
};
}
Returns the Adapter position of the item represented by this ViewHolder.
I have very little experience with Java, I write only in Kotlin. Here is what I have come up with.
Setting the click-events within the Adapter itself is not the best practise.According to the recommended way you should add a callback method and let the Activity
\ Fragment to which the Recycler is attached handle after the click events.
How to Proceed,
Step 1: Create an Interface which loosely binds your Adapter to Activity or Fragment.
interface AdapterListener{
void afterAdapterItemClicked(int adapterPosition);
}
This Interface can be created within Adapter itself as an inner member.
Step 2: Let the Activity or Fragment to which the Recycler is attached implement this Interface,So let assume your Activity is named as MenuActivity
class MenuActivity extends Activity implements AdapterListener{
}
Step 3: Now inside the Activity / Fragment implement the override method
#Override
void afterAdapterItemClicked(int adapterPosition){
switch(adapterPosition) {
case 0: // Move to activity1
break;
case 1: // Move to activity2
break;
}
}
Step 4 : Now calling the method afterAdapterClicked() after the click event
public static class ImageViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
ImageView imagess;
TextView titless;
public ImageViewHolder(View itemView) {
super(itemView);
imagess = itemView.findViewById(R.id.image);
titless = itemView.findViewById(R.id.title);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mListener.afterAdapterItemClicked(getAdapterPosition());
}
}
Step 5: Now to all the curious faces thinking, where in the world mListener landed from, don't worry I saved it for the last.
Now when you create the RecyclerAdapter object(instance) inside your Activity / Fragment you need to pass the current context or this in its constructor.
RecyclerAdapter(arrayOfImages,this);
Now create a new state variable inside your RecyclerAdapter class such as
private AdapterListener mListener;
And then in the constructor of RecyclerAdapter you need to add a variable of type
AdapterListener like this and then assign mListener the received value
public RecyclerAdapter(int[] images,AdapterListener mListener){
this.images = images;
this.mListener = mListener;
}
And then use mListener inside your inner class ImageViewHolder.
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");
}
Here's my problem:
I have an AlbumActivity that lists all the albums name using RecyclerView.
When one item is clicked it will go to ImagesActivity where all of the images inside the Album will be listed. I also used RecyclerView. ImagesActivity has a toolbar menu that can add multiple images in case the user wants to add another images to the album. When the menu is clicked another activity will be opened to add images path to the database.
My problem is that when I go back to the ImagesActivity the images do not appear. The images will only appear when I only go again to AlbumActivity to view again the album's images. How can I notify the change quickly in the ImagesActivity.
Here's my Adapter:
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
static List<GettersSetters> dbList;
static Context context;
ImageAdapter(Context context, List<GettersSetters> dbList) {
this.dbList = new ArrayList<GettersSetters>();
this.context = context;
this.dbList = dbList;
}
#Override
public ImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_image, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(ImageAdapter.ViewHolder holder, int position) {
File imageFile = new File(dbList.get(position).getPath());
if(imageFile.exists()){
Bitmap img = decodeBitmapWithSize(dbList.get(position).getPath(),300,150, true);
holder.imageGallery.setImageBitmap(img);
}else{
holder.imageGallery.setImageResource(R.drawable.not_found);
}
}
#Override
public int getItemCount() {
return dbList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imageGallery;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
imageGallery = (ImageView) itemLayoutView.findViewById(R.id.img_row);
itemLayoutView.setOnClickListener(this);
itemLayoutView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(context,"Delete Image",Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public void onClick(View v) {
}
}
You will need to refresh the dbList after add images path to the database.
When you go back to the Images Activity, you get new dbList from database in onActivityResult. And you can refresh the dbList as follows:
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
...
public void updateList(List<GettersSetters> dbList) {
this.dbList.clear();
this.dbList.addAll(dbList);
notifyDataSetChanged();
}
}
The most common way of doing it is to instantiate your List and Adapter in your activity, and call notifyDataSetChanged on your adapter whenever you change the data in the list.
For example, in your Activity class...
List<GetterSetter> list;
ImageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList();
adapter = new ImageAdapter(this, list);
// you will also need to attach your adapter to your recyclerview.
// when you are ready to modify/add/delete items from the list, just do it and call notifyDataSetChanged
list.add(new GetterSetter());
adapter.notifyDataSetChanged(); // This will update your recyclerview to show one item, instead of an empty list
}
In short, you obviously pass your Adapter a List. Any time you change any data in the list, make sure to call notifyDataSetChanged() on the adapter object.
when coming back to Images Activity in onResume method call like this
public void onResume{
youradapter.refreshrecyclerview(); // implement this method in adpater or simply call here
adpater.notifiDataSetChanged();
}
In adpater implement this method,
public void refreshrecyclerview(){
notifiDataSetChanged();
}
once you add the images, are you calling notifydatasetchanged() ? https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#notifyDataSetChanged()
this needs to be called in your ImagesActivity after you add your images to the dbList.
Please read the documentation in the above link to understand notifydatasetchanged()
This method basically informs the Adapter that the data in the dbList is updated and hence it has to refresh the UI.
I have an activity lets call it Activity 1 and there we will have a ListView composed by Player objetcs. When you click on a ListView_item (on a Player) a new activity starts, lets call it Activity 2. What I want is:
Activity 1 sends to Activity 2 player's name and player's race. In Activity 2 the user could edit that (player's name and player's race) and when the user click on Confirm Ativity 2 sends to Activity 1 the player's name and player's race even I the user has not edited it (in that case it would send the previus that Activity 1 has sended to Activity 2).
The problem is that when I'm suposse to use startActivityForResult I'm into ListViewAdapter class and using context.start... startActivityForResult doesn't appears.
public class AdaptadorJugadores extends BaseAdapter implements ListAdapter {
private ArrayList<Jugador> list = new ArrayList<Jugador>();
private Context context;
public AdaptadorJugadores(ArrayList<Jugador> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_lista_jugadores, null);
}
//Handle TextView and display string from your list
TextView TextoNombreJugador = (TextView)view.findViewById(R.id.etNombreJugador);
TextoNombreJugador.setText(list.get(position).getNombre());
if (list.get(position).getGenero() == "Hombre"){
TextoNombreJugador.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_face_black_24dp, 0, 0, 0);
}else{
TextoNombreJugador.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_face_black_girl24dp, 0, 0, 0);
}
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.btEliminarJugador);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
/*addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});*/
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(context, VistaJugador.class);
intent.putExtra("Nombre",(list.get(position).getNombre()));
intent.putExtra("Genero",(list.get(position)).getGenero());
// Start SingleItemView Class
}
});
return view;
}
}
You could use the ListView's setOnItemClickListener(AdapterView.OnItemClickListener listener) method and in there you could start the activity using startActivityForResult.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the data to pass to the activity based on the position clicked
Intent intent = new Intent(...);
intent.setExtra(...);
startActivityForResult(...);
}
});
Alternatively, you could pass the Activity to your adapter and use that instead of a context, but the first solution is preferable.
I suggest you to pass the context from the Activity to the Adapter, then store it in a local variable. After that, you can just use it to startActivityForResult, but note that you have to implement the onActivityResultMethod. My suggestion is that you use an interface, then pass the ID of the selected item and call the startActivityForResult() in the Activity.
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.