У меня есть приложение для Android, которое должно открыть действие при нажатии кнопки, но когда я нажимаю на него, приложение вылетает с сообщением «Попытка вызвать виртуальный метод». Вот мой Кодекс.Ошибка приложения при нажатии кнопки Нажмите «Попытка вызвать виртуальный метод»
MainClass.java
public class MainActivity extends ActionBarActivity {
Button Notify;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Notify = (Button)findViewById(R.id.notify);
Notify.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, DisplayPush.class);
startActivity(intent);
}
});
}
Моя другая деятельность класса
DisplayPush.java
public class DisplayPush extends Activity {
@Override
public void onBackPressed(){
Intent myIntent = new Intent(DisplayPush.this,MainActivity.class);
startActivity(myIntent);
// overridePendingTransition(R.anim.from_middle, R.anim.to_middle);
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
TextView notification_title = (TextView) findViewById(R.id.title);
TextView notification_message = (TextView) findViewById(R.id.message);
ParseAnalytics.trackAppOpened(getIntent());
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String jsonData = extras.getString("com.parse.Data");
try{
JSONObject notification = new JSONObject(jsonData);
// String title = notification.getString("push_hash");
String message = notification.getString("alert");
// notification_title.setText(title);
notification_message.setText(message);
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), "Something went wrong with the notification", Toast.LENGTH_SHORT).show();
}
}
Я определил acitivities в моем манифесте. Это ловушка.
03-21 06:51:35.157: E/AndroidRuntime(3042): FATAL EXCEPTION: main
03-21 06:51:35.157: E/AndroidRuntime(3042): Process: hasan.parsereceiveandshow, PID: 3042
03-21 06:51:35.157: E/AndroidRuntime(3042): java.lang.RuntimeException: Unable to start activity ComponentInfo{hasan.parsereceiveandshow/hasan.parsereceiveandshow.DisplayPush}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
Что я должен редактировать в коде? –
@penta: см. Мой ответ на редактирование –
@penta: добавьте проверку «null», а также используйте «extras.containsKey» для проверки ключа, присутствующего в Bundle или нет, до доступа к значению –