android - 按下启动另一个 Activity 的按钮时应用程序崩溃

标签 android android-activity crash buttonclick

就像标题所说,当我按下按钮更改 Activity 时,我的应用程序崩溃了。它在 Eclipse 中没有显示任何错误,并且最初打开,但当我按下按钮时关闭。最初,该应用程序根本无法打开,但我在 onClick() 中设置了变量,使其能够打开。

list

 <application
    android:allowBackup="true"
    android:icon="@drawable/globe"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.geoquizlab1solution.QuizActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  <activity android:screenOrientation="unspecified" android:name="com.example.geoquizlab1solution.SportsQuiz"/>
    </application>

第一个 Activity 的类ActivityQuiz.java:

package com.example.geoquizlab1solution;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class QuizActivity extends Activity {

private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private ImageButton mPreviousButton;
private TextView mQuestionTextView;
private Button mResetButton;
private Button mSportsButton;
private Button mGeoButton;
//private Button mMusicButton;
private int counter = 0;


private TrueFalse[] mQuestionBank = new TrueFalse[] {
        new TrueFalse(R.string.question_oceans, true),
        new TrueFalse(R.string.question_mideast, false),
        new TrueFalse(R.string.question_africa, false),
        new TrueFalse(R.string.question_americas, true),
        new TrueFalse(R.string.question_asia, true)
};


private int mCurrentIndex=0;

private void updateQuestion(){
    int question = mQuestionBank[mCurrentIndex].getQuestion();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
    int messageResId = 0;

    SharedPreferences app_preferences = 
            PreferenceManager.getDefaultSharedPreferences(this);

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_toast;
        counter++;

    }
        else {
            messageResId = R.string.incorrect_toast;
        }
     SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("count", counter);
    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
    Toast.makeText(this,"Score:" + counter, Toast.LENGTH_SHORT).show();
    editor.commit();
        }

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


    mGeoButton = (Button)findViewById(R.id.geo_button);
    mGeoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            counter = 0;
            Toast.makeText(getApplicationContext(), "Score: 0",
                    Toast.LENGTH_SHORT).show();
            mCurrentIndex = 0;
            updateQuestion();
        }
    });

    mSportsButton = (Button)findViewById(R.id.sports_button);
    mSportsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent1 = new Intent(QuizActivity.this, SportsQuiz.class);
            if (intent1 != null) {
                startActivity(intent1);
            }
        }
    });

  /*  mMusicButton = (Button)findViewById(R.id.music_button);
    mMusicButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(this, MusicQuiz.java);
        }
    });*/

    mTrueButton = (Button)findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);

        }
    }); 

    mFalseButton = (Button)findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
            }
    });
    mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
    ((View) mQuestionTextView) .setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mPreviousButton = (ImageButton)findViewById(R.id.previous_button);
    ((View) mPreviousButton) .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                if (mCurrentIndex != 0) {
                    mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
                updateQuestion();
                }
                else {
                    mCurrentIndex = (mCurrentIndex + 4) % mQuestionBank.length;
                }
        }
    });
    updateQuestion();


    mNextButton = (ImageButton)findViewById(R.id.next_button);
    ((View) mNextButton).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
        });
    updateQuestion();

    mResetButton = (Button)findViewById(R.id.reset_button);
    ((View) mResetButton).setOnClickListener(new View.OnClickListener () {
        @Override
        public void onClick(View v) {
            counter = 0;
            Toast.makeText(getApplicationContext(), "Score: 0",
                    Toast.LENGTH_SHORT).show();
            mCurrentIndex = 0;
            updateQuestion();
        } 
    });
}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_quiz, menu);
    return true;
}

}

SportsQuiz.java:

package com.example.geoquizlab1solution;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


public class SportsQuiz extends Activity {
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private ImageButton mPreviousButton;
private TextView mQuestionTextView;
private Button mResetButton;
private Button mSportsButton;
private Button mGeoButton;
//private Button mMusicButton;
private int counter = 0;
Intent intent1 = getIntent();
Intent intent = new Intent(this, SportsQuiz.class);


private TrueFalse[] mQuestionBank = new TrueFalse[] {
        new TrueFalse(R.string.question_baseball, true),
        new TrueFalse(R.string.question_football, false),
        new TrueFalse(R.string.question_basketball, false),
        new TrueFalse(R.string.question_hockey, true),
        new TrueFalse(R.string.question_soccer, true)
};


private int mCurrentIndex=0;

private void updateQuestion(){
    int question = mQuestionBank[mCurrentIndex].getQuestion();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
    int messageResId = 0;

    SharedPreferences app_preferences = 
            PreferenceManager.getDefaultSharedPreferences(this);

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_toast;
        counter++;

    }
        else {
            messageResId = R.string.incorrect_toast;
        }
     SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("count", counter);
    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
    Toast.makeText(this,"Score:" + counter, Toast.LENGTH_SHORT).show();
    editor.commit();
        }
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz); 


    mGeoButton = (Button)findViewById(R.id.geo_button);
    mGeoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            counter = 0;
            Toast.makeText(getApplicationContext(), "Score: 0",
                    Toast.LENGTH_SHORT).show();
            mCurrentIndex = 0;
            updateQuestion();
        }
    });

    mSportsButton = (Button)findViewById(R.id.sports_button);
    mSportsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(intent1);
        }
    });

   /* mMusicButton = (Button)findViewById(R.id.music_button);
    mMusicButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(this, MusicQuiz.java);
        }
    }); */

    mTrueButton = (Button)findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);

        }
    }); 

    mFalseButton = (Button)findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
            }
    });
    mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
    ((View) mQuestionTextView) .setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mPreviousButton = (ImageButton)findViewById(R.id.previous_button);
    ((View) mPreviousButton) .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                if (mCurrentIndex != 0) {
                    mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
                updateQuestion();
                }
                else {
                    mCurrentIndex = (mCurrentIndex + 4) % mQuestionBank.length;
                }
        }
    });
    updateQuestion();


    mNextButton = (ImageButton)findViewById(R.id.next_button);
    ((View) mNextButton).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
        });
    updateQuestion();

    mResetButton = (Button)findViewById(R.id.reset_button);
    ((View) mResetButton).setOnClickListener(new View.OnClickListener () {
        @Override
        public void onClick(View v) {
            counter = 0;
            Toast.makeText(getApplicationContext(), "Score: 0",
                    Toast.LENGTH_SHORT).show();
            mCurrentIndex = 0;
            updateQuestion();
        } 
    });
}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_quiz, menu);
    return true;
}

}

这是日志:

04-04 20:48:42.600: E/AndroidRuntime(25939): FATAL EXCEPTION: main

04-04 20:48:42.600: E/AndroidRuntime(25939): Process: com.example.geoquizlab1solution, PID: 25939

04-04 20:48:42.600: E/AndroidRuntime(25939): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.geoquizlab1solution/com.example.geoquizlab1solution.SportsQuiz}: java.lang.NullPointerException

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2124)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.app.ActivityThread.access$800(ActivityThread.java:139)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.os.Handler.dispatchMessage(Handler.java:102)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.os.Looper.loop(Looper.java:136)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.app.ActivityThread.main(ActivityThread.java:5097)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at java.lang.reflect.Method.invokeNative(Native Method)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at java.lang.reflect.Method.invoke(Method.java:515)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at dalvik.system.NativeStart.main(Native Method)

04-04 20:48:42.600: E/AndroidRuntime(25939): Caused by: java.lang.NullPointerException

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.content.ComponentName.<init>(ComponentName.java:77)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.content.Intent.<init>(Intent.java:3823)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at com.example.geoquizlab1solution.SportsQuiz.<init>(SportsQuiz.java:28)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at java.lang.Class.newInstanceImpl(Native Method)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at java.lang.Class.newInstance(Class.java:1208)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.app.Instrumentation.newActivity(Instrumentation.java:1084)

04-04 20:48:42.600: E/AndroidRuntime(25939):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2115)

04-04 20:48:42.600: E/AndroidRuntime(25939):    ... 11 more

最佳答案

您无法在定义 Intent 的地方分配对象

所以将此行放入您的 Activity 生命周期方法中,例如 onCreate 或任何其他方法,

只需在Oncreate方法中写入这一行

intent = new Intent(this, SportsQuiz.class); Intent1 = getIntent();

关于android - 按下启动另一个 Activity 的按钮时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36416749/

相关文章:

android - 在 Android 中将表名作为字符串传递给 SQLiteDatabase 删除函数

asp.net - 如何检测移动网络浏览器及其屏幕大小

android - 暂停时 Activity 崩溃

jquery - 重量级 Jquery 幻灯片在桌面上运行缓慢,在 ipad 2、android ics 和 iphone 上崩溃

qt - qDebug() 的奇怪行为导致应用程序崩溃

ios - 如何解决内存崩溃

android - 如何在android中获取联系网站信息?

java - 如何在 Android 上为 Room 库设置 proguard 规则

android - 如何从 Fragment 中清除 Android 中的 WindowManager 标志

android - 从堆栈恢复重新创建的 Activity 时未调用 Activity onStart()