Priya Raj
Priya Raj

Reputation: 3

Getting data from listview and checking with if else

In my application I'm using a listview. I need to perform an if else check with selected data from listview. For that I created the following code. When I displayed the selected value, it displays correctly. But it isn't checked within the loop.

mainListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String level = (String) (mainListView.getItemAtPosition(myItemInt));
        //  Toast.makeText(Listactivity.this, "" + level, 2000).show(); 

        if(level == "level-1")
        {
            Toast.makeText(Listactivity.this, "" + "selected levelel1", 2000).show();
        }
        else if(level == "level-2")
        {
         Toast.makeText(Listactivity.this, "" + "selected level 2", 2000).show();
        }
        else if(level == "level-3")
        {
         Toast.makeText(Listactivity.this, "" + "selected level3", 2000).show();
        }
        else
        {
         System.out.println("Level s not available");
        }

        }

     });
  }

Upvotes: 0

Views: 952

Answers (3)

Nikhil
Nikhil

Reputation: 16196

Please try compare String do like this

if(level.equalsIgnoreCase("level-1")){
}

Upvotes: 2

Samir Mangroliya
Samir Mangroliya

Reputation: 40416

Use .equals().Because == compares Strings Refrences not Characters of strings.

Compares Strings using .equals() when String is object.When you declare string as String literal then you can compare strings using ==

 if(level.equals("level-1"))
        {
            Toast.makeText(Listactivity.this, "" + "selected levelel1", 2000).show();
        }
        else if(level.equals("level-2"))
        {
         Toast.makeText(Listactivity.this, "" + "selected level 2", 2000).show();
        }

Upvotes: 1

Rasel
Rasel

Reputation: 15477

To compare String do like this

if(level.equals("level-1")){
}

Upvotes: 1

Related Questions