willard5991 willard5991 - 28 days ago 6
Android Question

Button will not change Activities using Eclipse

I have been working on an android app for a while now, and just recently I have hit a wall in the code. For some reason, when I hit a button in the app that should change the activity, it keeps saying "the application has stopped unexpectedly" and exits out. I have done a lot of research on the subject of how to do it and tried many variations on the code to try and get it to work and still i get the error. here is what I have been using:

semester = (Button) findViewById(R.id.bSemester);
semester.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent isemester = new Intent(getApplicationContext(),MainActivity.class);
startActivity(isemester);
}
});


So are there any problems with this code? and also, is there some code that must be placed in the second activity java file (in this case MainActivity) to get it to change?

Edit:
I looked at the LogCat like Oren said and saw that it was saying

"java.lang.RuntimeException: Unable to start activity ComponentInfo{ com.william.android.test/com.william.android.test.MainActivity}: java.lang.NullPointerException"

This is what I have in my Test Manifest:

<activity
android:name=".MainActivity" android:label="Semester Grade" >
<intent-filter>
<action android:name="com.william.android.test.MainActivity" />
<catagory android:name="android.intent.catagory.DEFAULT" />
</intent-filter>
</activity>


here is what I have under OnCreate() :

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

gradehave = (EditText) findViewById(R.id.etGradeHave);
gradewant = (EditText) findViewById(R.id.etGradeWant);
finalworth = (EditText) findViewById(R.id.etFinalWorth);

needed = (TextView) findViewById(R.id.tvNeeded);
calc = (Button) findViewById(R.id.bCalc);
calc.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
gw = Double.parseDouble(gradewant.getText().toString());
gh = Double.parseDouble(gradehave.getText().toString());
pf = Double.parseDouble(finalworth.getText().toString());
pf = (pf/100);
pg = (1 - pf);
n = (gw - (pg * gh)) / pf;
needed.setText(" " + n);

}

});
home.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, Welcome_Screen.class);
startActivity(i);
}
});

}


Thanks

Answer Source

In your oncreate method, you didn't define 'home'. If its a button, you should first findviewbyid it before setting click listener.