Search code examples
javalistviewglobal-variablesonclicklistener

global variable inside listview onClickListerner java


Can someone look at what I'm doing wrong here please. Declared global variable outside of method listView onClickListener and tried to assign a value to this variable inside the method. Variable log returning values inside the method but null outside.

public static String selected;

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {     
    selected = ((TextView) view.findViewById(R.id.textviewid)).getText().toString();
    Toast.makeText(getApplicationContext(), selected, Toast.LENGTH_SHORT).show();
    Log.i("Selected", "Value: "+selected);
}
});

Log.i("Selected2", "Value: "+selected);

And Log is showing:

06-22 11:58:16.597 10063-10063/com.example.app I/Selected2: Value: null
06-22 11:58:28.487 10063-10063/com.example.app I/Selected: Value: Value1

Solution

  • Your code executes first without executing onItemClick(), java listens for this event and will only execute when the item is clicked. So the Log with "Selected2" is executed first and prints null as there is no value assigned to it yet. And onItemClick() will only execute when the item will be clicked. Most probably you will be clicking after java has gone through the Log with "Selected2". SO when you click the item it assigns a value and the value is printed using Log that is inside onItemClick()