user1410081
user1410081

Reputation:

ANDROID can get selected item string

I've got problem with my listview adapter.

Please check my code below:

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    // TODO Auto-generated method stub
    String selected;

    selected = parent.getItemAtPosition(position).toString();

    if( selected == "Apple" ){
        Intent apple = new Intent(Fruits.this, Apples.class);
        startActivity(apple);
    }
    else if( selected == "Apricot" ){
        Intent apricot = new Intent(Fruits.this, Apricots.class);
        startActivity(apricot);
    }
    else if( selected == "Avocado" ){
        Intent avocado = new Intent(Fruits.this, Avocado.class);
        startActivity(avocado);
    }

} // end of OnItemClick method

Whenever I select a row, it's throwing a nullpointerexception on this line:

        selected = parent.getItemAtPosition(position).toString();

What is the problem here? please help. thanks.

Upvotes: 0

Views: 2699

Answers (6)

Delmirio Segura
Delmirio Segura

Reputation: 1691

If your adapter contain model, use this code:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        itemDrawer seleted = (itemDrawer) parent.getItemAtPosition(position);

        Toast.makeText(getApplicationContext(), seleted.getTitle(), Toast.LENGTH_SHORT).show();
    }

Upvotes: 0

MKJParekh
MKJParekh

Reputation: 34301

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    TextView tv = v.findViewById(R.id.myTitle);
    tv.getText().toString(); // String
} 

You can get child view of your list item like the above way.

Upvotes: 0

Sahil Mahajan Mj
Sahil Mahajan Mj

Reputation: 11141

As per your excpetion use the following code,

selected = parent.getItem(position).toString();

Also you have used,

if( selected == "Apple" ){

Its not correct way to compare strings, Instead of it use,

if( selected.equals("Apple") ){

Upvotes: 0

Chintan Rathod
Chintan Rathod

Reputation: 26034

For comparing equality of string ,We Use equals() Method. There are two ways of comparison in Android.

One is "==" operator and another "equals()" method .

"==" compares the reference value of string object whereas equals() method compares content of the string object. .

use

selected.equals("your string")

Upvotes: 0

Nikola Despotoski
Nikola Despotoski

Reputation: 50538

Change

 selected = parent.getItemAtPosition(yourListView.getFirstVisiblePosition() + position).toString();

Upvotes: 0

Bhavesh Patadiya
Bhavesh Patadiya

Reputation: 25830

i think you should write

 if( selected.equals("Apple")){
//Do your Code
}

instead of

 if( selected == "Apple" ){
}

Upvotes: 1

Related Questions