java - 无法启动 Activity ?

标签 java android android-intent authentication android-asynctask

在添加异步任务之前,我对代码进行了一些更改,我的应用程序可以正确地从远程服务器验证用户名和密码,但在登录成功消息消失时无法启动其他 Activity 。有人建议我添加异步任务,现在我已经添加了该任务,但是当我输入正确的用户名和密码时,它会停止工作。当我输入错误的用户名和密码时,其工作正常,显示错误的用户名密码消息。如果有人知道会发生什么错误,请帮助我。

代码-

public class LoActivity extends Activity {

    Intent i;
    Button signin;
    TextView error;
    CheckBox check;
    String name = "", pass = "";
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences;
    List<NameValuePair> nameValuePairs;
    EditText editTextId, editTextP;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        signin = (Button) findViewById(R.id.signin);
        editTextId = (EditText) findViewById(R.id.editTextId);
        editTextP = (EditText) findViewById(R.id.editTextP);
        app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        check = (CheckBox) findViewById(R.id.check);
        String Str_user = app_preferences.getString("username", "0");
        String Str_pass = app_preferences.getString("password", "0");
        String Str_check = app_preferences.getString("checked", "no");
        if (Str_check.equals("yes")) {
            editTextId.setText(Str_user);
            editTextP.setText(Str_pass);
            check.setChecked(true);
        }

        signin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                name = editTextId.getText().toString();
                pass = editTextP.getText().toString();
                String Str_check2 = app_preferences.getString("checked", "no");
                if (Str_check2.equals("yes")) {
                    SharedPreferences.Editor editor = app_preferences.edit();
                    editor.putString("username", name);
                    editor.putString("password", pass);
                    editor.commit();
                }
                if (name.equals("") || pass.equals("")) {
                    Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
                } else {
                    new LoginTask().execute();
                }
            }
        });

        check.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks, depending on whether it's now
                // checked
                SharedPreferences.Editor editor = app_preferences.edit();
                if (((CheckBox) v).isChecked()) {
                    editor.putString("checked", "yes");
                    editor.commit();
                } else {
                    editor.putString("checked", "no");
                    editor.commit();
                }
            }
        });
    }

    public void Move_to_next() {
        startActivity(new Intent(this, QuestionnActivity.class));
          }

    @SuppressLint("NewApi")
    private class LoginTask extends AsyncTask <Void, Void, String> {
        @SuppressLint("NewApi")
        @Override
        protected void onPreExecute() 
        {

            super.onPreExecute();
            // Show progress dialog here
        }

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://abc.com/login1.php");
                // Add your data
                nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                // Execute HTTP Post Request
                response = httpclient.execute(httppost);
                inputStream = response.getEntity().getContent();
                data = new byte[256];
                buffer = new StringBuffer();
                int len = 0;
                while (-1 != (len = inputStream.read(data))) {
                    buffer.append(new String(data, 0, len));
                }

                inputStream.close();
                return buffer.toString();
            } 
            catch (Exception e) 
            {
                e.printStackTrace();

            }
            return "";
        }

        @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Hide progress dialog here

            if (buffer.charAt(0) == 'Y') {
                Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                Move_to_next();
            } else {
                Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
            }
        }
    }
}  

登录猫-

09-24 07:59:32.818: E/AndroidRuntime(17602): FATAL EXCEPTION: main
09-24 07:59:32.818: E/AndroidRuntime(17602): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abc.cyk/com.abc.cyk.QuestionActivity}: java.lang.NullPointerException
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.os.Looper.loop(Looper.java:137)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.app.ActivityThread.main(ActivityThread.java:5041)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at java.lang.reflect.Method.invokeNative(Native Method)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at java.lang.reflect.Method.invoke(Method.java:511)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at dalvik.system.NativeStart.main(Native Method)
09-24 07:59:32.818: E/AndroidRuntime(17602): Caused by: java.lang.NullPointerException
09-24 07:59:32.818: E/AndroidRuntime(17602):    at com.abc.cyk.QuestionActivity.processScreen(QuestionActivity.java:41)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at com.abc.cyk.QuestionActivity.onCreate(QuestionActivity.java:33)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.app.Activity.performCreate(Activity.java:5104)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
09-24 07:59:32.818: E/AndroidRuntime(17602):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
09-24 07:59:32.818: E/AndroidRuntime(17602):    ... 11 more
09-24 07:59:38.557: I/Process(17602): Sending signal. PID: 17602 SIG: 9

问题 Activity -

public class QuestionActivity extends Activity implements OnClickListener{

    private Question currentQ;
    private GamePlay currentGame;
    private CountDownTimer counterTimer;

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.question);
                processScreen();
         }
                /**
         * Configure current game and get question
         */
         private void processScreen()
         {
        currentGame = ((CYKApplication)getApplication()).getCurrentGame();
        currentQ = currentGame.getNextQuestion();
        Button nextBtn1 = (Button) findViewById(R.id.answer1);
        nextBtn1.setOnClickListener(this);
        Button nextBtn2 = (Button) findViewById(R.id.answer2);
        nextBtn2.setOnClickListener(this);
        Button nextBtn3 = (Button) findViewById(R.id.answer3);
        nextBtn3.setOnClickListener(this);
        Button nextBtn4 = (Button) findViewById(R.id.answer4);
        nextBtn4.setOnClickListener(this);
        Button nextBtn5 = (Button) findViewById(R.id.answer5);
        nextBtn5.setOnClickListener(this);
        /**
         * Update the question and answer options..
         */
        setQuestions();

    }


    /**
     * Method to set the text for the question and answers from the current games
     * current question
     */
    private void setQuestions() {
        //set the question text from current question
        String question = Utility.capitalise(currentQ.getQuestion());
        TextView qText = (TextView) findViewById(R.id.question);
        qText.setText(question);

        //set the available options
        List<String> answers = currentQ.getQuestionOptions();
        TextView option1 = (TextView) findViewById(R.id.answer1);
        option1.setText(Utility.capitalise(answers.get(0)));

        TextView option2 = (TextView) findViewById(R.id.answer2);
        option2.setText(Utility.capitalise(answers.get(1)));

        TextView option3 = (TextView) findViewById(R.id.answer3);
        option3.setText(Utility.capitalise(answers.get(2)));

        TextView option4 = (TextView) findViewById(R.id.answer4);
        option4.setText(Utility.capitalise(answers.get(3)));

        int score = currentGame.getScore();
        String scr = String.valueOf(score);
        TextView score1 = (TextView) findViewById(R.id.score);
        score1.setText(scr);

        counterTimer=new CountDownTimer(15000, 1000) {
            public void onFinish() {                
                if(currentGame.getRound()==20)
                    System.exit(0);
                currentGame.decrementScore();
                processScreen();
                             }

            public void onTick(long millisUntilFinished) {
                TextView time = (TextView) findViewById(R.id.timers);
                time.setText( ""+millisUntilFinished/1000);
                                }
        };
        counterTimer.start();
    }


    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void onClick(View arg0) {
        //Log.d("Questions", "Moving to next question");
        if(arg0.getId()==R.id.answer5)
        {
        new AlertDialog.Builder(this)
        .setMessage("Are you sure?")
        .setCancelable(true)
        .setPositiveButton("Yes",
         new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,
         int id) {
                finish();
                 }
             }).setNegativeButton("No", null).show();

                }

        else
        {
            if(!checkAnswer(arg0)) return;  

        /**
         * check if end of game
         */
        if (currentGame.isGameOver()){
            //Log.d("Questions", "End of game! lets add up the scores..");
            //Log.d("Questions", "Questions Correct: " + currentGame.getRight());
            //Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
            Intent i = new Intent(this, EndgameActivity.class);
            startActivity(i);
            finish();
        }
            else
            {
            Intent i = new Intent(this, QuestionActivity.class);
                        finish();
                        startActivity(i);
        }
        }
      }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
        case KeyEvent.KEYCODE_BACK :
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    /**
     * Check if a checkbox has been selected, and if it
     * has then check if its correct and update gamescore
     */
    private boolean checkAnswer(View v) {
        final Button b = (Button) v;
        String answer = b.getText().toString();
         counterTimer.cancel();
         b.setBackgroundResource(R.drawable.ans);
         b.setEnabled(false);
        //Log.d("Questions", "Valid Checkbox selection made - check if correct");
            if (currentQ.getAnswer().equalsIgnoreCase(answer))
                {
                b.setBackgroundResource(R.drawable.ansgreen);
                //Log.d("Questions", "Correct Answer!");
                currentGame.incrementScore();
                }

            else{
                b.setBackgroundResource(R.drawable.ansred);
                //Log.d("Questions", "Incorrect Answer!");
                currentGame.decrementScore1();
                            }
            return true;
        }

}

最佳答案

将评论转换为答案

通过查看 logcat,我们可以看到问题出在 QuestionActivity 的第 41 行。所以我们知道 currentGamenull

您需要在此之前设置断点,并查看是什么导致该断点为 null。您可能已经发现其他变量/对象为null,这最终导致NPE

关于java - 无法启动 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19031225/

相关文章:

Java 线程 - 内存一致性错误

java - mysql写入后立即读取数据?

java - 如何更改 Jena 中 TriplePath 的节点?

java - 将 Intent 从 Activity 传递到扩展应用程序的类

java - 检测未使用的 Spring bean

android - ProgressBar 不显示,android

android - 单击登录按钮以及从网络服务器完成验证时创建进度条

android - 两个相邻的 float 操作按钮

android - 接到来电时如何调用 Activity 。

android - 如何通过非 Activity 类从另一个 Activity 获取数据