[android] Android ListView with onClick items

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

This question is related to android listview methods android-activity elements

The answer is


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)

I was able to go around the whole thing by replacing the context reference from this or Context.this to getapplicationcontext.


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


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")

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.


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);
  }

});

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to listview

How to add a ListView to a Column in Flutter? Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView` Best way to update data with a RecyclerView adapter Android Recyclerview vs ListView with Viewholder Get clicked item and its position in RecyclerView How to show an empty view with a RecyclerView? NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference RecyclerView vs. ListView How to implement endless list with RecyclerView? Recyclerview and handling different type of row inflation

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items

Examples related to elements

comparing elements of the same array in java Android ListView with onClick items How to return a specific element of an array? Best way to get child nodes Skipping every other element after the first jquery find element by specific class when element has multiple classes Get multiple elements by Id How to get span tag inside a div in jQuery and assign a text? How to set DOM element as the first child? Number of elements in a javascript object