Reputation: 15
I made an Android Application. Eclipse isn't reporting me what errors are there in my code.
But if I run my project then emulator displays:
emulator error http://s2.ipicture.ru/uploads/20121106/466GCZH9.png
My Java code is (MainActivity.java
):
package ru.startandroid.develop.AppLog;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
TextView myText = (TextView) findViewById(R.id.myText);
Button myBtnCancel = (Button) findViewById(R.id.myBtnCancel);
Button myBtnOK = (Button) findViewById(R.id.myBtnOK);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.myBtnCancel:
myText.setText("Нажата кнопка Cancel");
break;
case R.id.myBtnOK:
myText.setText("Нажата кнопка ОК");
break;
}
}
}
Upvotes: 1
Views: 122
Reputation: 66637
Change your code like below:
Declare variables at instance level and assign values inside onCreate()
public class MainActivity extends Activity implements OnClickListener{
TextView myText = null;
Button myBtnCancel = null;
Button myBtnOK = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView) findViewById(R.id.myText);
myBtnCancel = (Button) findViewById(R.id.myBtnCancel);
myBtnOK = (Button) findViewById(R.id.myBtnOK);
}
Upvotes: 0
Reputation: 5153
You need to bind the Widgets (TextView and Buttons) calling findById
after the setContentView
method, because depends of it:
TextView myText;
Button myBtnCancel;
Button myBtnOK;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView) findViewById(R.id.myText);
myBtnCancel = (Button) findViewById(R.id.myBtnCancel);
myBtnOK = (Button) findViewById(R.id.myBtnOK);
}
Upvotes: 1
Reputation: 86948
You can only use findViewById()
after calling setContentView()
:
public class MainActivity extends Activity implements OnClickListener{
TextView myText;
Button myBtnCancel;
Button myBtnOK;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView) findViewById(R.id.myText);
myBtnCancel = (Button) findViewById(R.id.myBtnCancel);
myBtnOK = (Button) findViewById(R.id.myBtnOK);
}
Upvotes: 2