Please, Help me...
public class TestActiv开发者_如何学Goity extends PreferenceActivity {
/********/
mTestPref = findPreference("test_preference");
mTestPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// TODO Auto-generated method stub
String Message = mMessagePref.getSummary().toString();
MainActivity main = new MainActivity();
main.execute(Message);
return true;
}
});
}
public class MainActivity extends Activity {
/************/
public void execute(String message) {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show(); // NullPointerExcepiton
}
}
11-04 16:50:12.317: ERROR/AndroidRuntime(19524): Uncaught handler: thread main exiting due to uncaught exception
11-04 16:50:12.356: ERROR/AndroidRuntime(19524): java.lang.NullPointerException
11-04 16:50:12.356: ERROR/AndroidRuntime(19524): at android.widget.Toast.<init>(Toast.java:89)
- Don't use
getBaseContext
. An Activity is a context. Just usethis
. - Verify that the string you're using is not null.
- You don't create Activity objects yourself. You need to have the operating system do that via
startActivity
.
Since the Main Activity is created by you, the base context is not set. Maybe you can add:
main.setBaseContext(this);
before
main.execute(Message);
But your whole program looks weird. Why do you need to create an activity to execute something? If you need to start another activity, then use startActivity(). If you need it to execute something immediately, you should pass those 'parameters' via the Intent.
You CAN'T just call new MyActivity(). That's not how activites are created. You can NEVER, EVER call new on a class that extends Activity.
You can't call instance methods of Activites from other classes.
精彩评论