public class MainActivity extends Activity {
TimePicker timePicker;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
//--Button view---
Button btnOpen = (Button)findViewById(R.id.btnSet);
btnOpen.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
"Time selected:" +
timePicker.getCurrentHour() +
":" + timePicker.getCurrentMinute(),
Toast.LENGTH_SHORT).show();
}
});
}
}
somebody explain me plz ?
Asked
Active
Viewed 636 times
0

sanjay
- 2,116
- 3
- 19
- 25
1 Answers
0
public class MainActivity extends Activity {
TimePicker timePicker;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
//--Button view---
Button btnOpen = (Button)findViewById(R.id.btnSet);
btnOpen.setOnClickListener(new OnClickListener() // <------- Inner class
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
"Time selected:" +
timePicker.getCurrentHour() +
":" + timePicker.getCurrentMinute(),
Toast.LENGTH_SHORT).show();
}
});
You're creating an anonymous class that extends the abstract OnClickListenerClass by providing an onClick method.
To fix, declare timePicker as final.
final TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);

Austin Hanson
- 21,820
- 6
- 35
- 41
-
but if i remove the TimePicker from the code TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker); timePicker.setIs24HourView(true); the code is working no need to declare as final...whats the matter..?will u explan me plz...? – sanjay Aug 06 '11 at 04:47
-
Just add **final** in front of the declaration within your onCreate method. _Or_ remove the local declaration and use your member variable (also with the same name...timePicker). – Austin Hanson Aug 06 '11 at 04:48
-
You have two timePicker variables - a locally scoped one declared within **onCreate** and a member variable ("package" scoped because you didn't specify private or public - which is unimportant here) variant. Chances are, the **onClick** method of your **OnClickListener** instance is calling the member variable since it can't see **onCreate**'s local one. – Austin Hanson Aug 06 '11 at 04:52