I am learning to make android applications and so kindly help me. I am making some application to learn touch inputs. So I decided to start with getting the touch location.
I made this application
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "in.manas.anurag.firstapp.MESSAGE";
final TextView textView = (TextView)findViewById(R.id.textView);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View touchView = findViewById(R.id.touchView);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
When I use the emulator to run this app, it crashes. However a small change in the application (namely removing "final TextView textView = (TextView)findViewById(R.id.textView);" from the class and putting it as a part of function onTouch makes the app work)
Can someone explain why the first code does not work?
Thank you.
-- The correct code:
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "in.manas.anurag.firstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View touchView = findViewById(R.id.touchView);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final TextView textView = (TextView)findViewById(R.id.textView);
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}