Search code examples
javaandroidgoogle-mapspolyline

Clicking polyline and display the result in android


I need some help. As you can see in my code. It seems I always get the result of else.

For Example: Result of string s is 1 after clicking the polyline. The result should be in the (s == "1") then execute the toast. But in the end it will always go to the else.

@Override
public void onPolylineClick(Polyline polyline) {
    // Flip the values of the red, green and blue components of the polyline's color.
    polyline.setColor(polyline.getColor() ^ 0x00ffffff);
    String s = polyline.getId().substring(2);

    if (s == "0")
    {
        Toast.makeText(getActivity(), "pl0 here" , Toast.LENGTH_SHORT).show();
    }
    else if (s == "1")
    {
        Toast.makeText(getActivity(), "pl1 here", Toast.LENGTH_SHORT).show();
    }

    else
    {
        Toast.makeText(getActivity(), "Inside ELSe", Toast.LENGTH_SHORT).show();
        Toast.makeText(getActivity(), "" + s, Toast.LENGTH_SHORT).show();
        Toast.makeText(getActivity(), "pl" + polyline.getId().substring(2), Toast.LENGTH_SHORT).show();
        Toast.makeText(getActivity(), "" + s + "==" + "pl" + polyline.getId().substring(2), Toast.LENGTH_LONG).show();
    }
}

Solution

  • Take care with == operator, Java doesn't recognize it in the same way:

    What’s the difference between equals() and ==?

    if (s.equals("0"))
    {
        Toast.makeText(getActivity(), "pl0 here" , Toast.LENGTH_SHORT).show();
    }
    else if (s.equals("1"))
    {
        Toast.makeText(getActivity(), "pl1 here", Toast.LENGTH_SHORT).show();
    }
    

    Both equals() method and == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compare reference or memory location of objects in the heap, whether they point to the same location or not .whenever we create any object using the operator new it will create new memory location for that object. So we use == operator to check memory location or address of two objects wheather they are same or not.

    You can read more at:

    http://www.java67.com/2012/11/difference-between-operator-and-equals-method-in.html#ixzz4bPGNw3SY