I am writing a test application which consists of:
2 buttons
1 Edittext
1 Textview
The first button “Random” writes a random name both in the EditText box and the TextView
(I have a class called RandomName which returns a string with a random name)
The second button “print” writes whatver is in the EditText into the TextView
The program crashes when I run it and i can’t figure out why. Any help would be appreciated
Layout image here: http://img824.imageshack.us/img824/3046/rndname.jpg
public class RandomNameTesteActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public EditText nomeEdt = (EditText)findViewById(R.id.editText1);
public String nomeStr = nomeEdt.toString();
public TextView nomeTest = (TextView) findViewById(R.id.textView1);
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button1:
//Put random name in EditText box and in TextView
RandomName RndName = new RandomName();
String rndNameStr = RndName.getName();
nomeTest.setText(rndNameStr);
break;
case R.id.button2:
//Print whatever is in EditText box to TextView
nomeTest.setText(nomeStr);
break;
}
}
}
EDIT: CHANGED CODE TO THE FOLLOWING: (it doesnt crash anymore but it doesnt work, as in the buttons do nothing)
public class RandomNameTesteActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText nomeEdt;
TextView nomeTest;
String nomeStr;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nomeEdt = (EditText)findViewById(R.id.editText1);
nomeStr = nomeEdt.toString();
nomeTest = (TextView) findViewById(R.id.textView1);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button1:
//Put random name in EditText box and in TextView
RandomName RndName = new RandomName();
String rndNameStr = RndName.getName();
nomeTest.setText(rndNameStr);
break;
case R.id.button2:
//Print whatever is in EditText box to TextView
nomeTest.setText(nomeStr);
break;
}
}
}
I believe the issue is with the following lines:
Change this to
Try that and see if it fixes your issue. You can’t look up your other views until you have set the contentview.
Also it helps if you post the stacktrace when asking a question