当前位置: 首页 > 面试题库 >

无法启动活动?

邢焕
2023-03-14
问题内容

在添加异步任务之前,我已经对代码进行了一些更改,我的应用html" target="_blank">程序可以正常运行其远程服务器上的身份验证用户名和密码,但是在登录成功消息消失后​​无法启动其他活动。有人建议我现在添加一个异步任务,但是我输入正确的用户名和密码后它将停止工作。当我输入错误的用户名和密码时,其工作正常将显示错误的用户名密码消息。如果有人能够知道会出现什么错误,请帮助我。

码-

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

QuestionnActivity-

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,我们可以看到问题出在的第41行QuestionActivity。所以我们知道那currentGamenull

您需要在此之前设置断点,然后查看导致该断点的原因null。您可能已经发现其他变量/对象null最终导致NPE



 类似资料:
  • 我已经搜索了这个错误,并找到了许多解决方案,但我无法解决这个问题,因为我是Android的初学者 舱单在下面 安装应用程序后,它第一次工作,但当我们关闭并重新打开时,它崩溃了,不幸的是,应用程序已经关闭,你有任何想法,它将非常感谢:) 谢了!

  • 错误是: 错误:(50,17)错误:没有为startActivities(Intent)方法Activity找到合适的方法。startActivities(Intent[],Bundle)不适用(实际和正式的参数列表长度不同)方法Activity.startActivities(Intent[])方法上下文twrapper.startactivities(Intent[],Bundle)不适用(实

  • MainFormular.java 在Android.app.activity.performCreate(activity_main_formular 洛克卡特

  • 我在运行android应用程序时遇到这个错误 05-25 23:58:44.251:E/AndroidRuntime(1128):java.lang.RuntimeException:无法启动activity ComponentInfo{info.AndroidHive.TabsSwipe/Info.AndroidHive.TabsSwipe.MainActivity}:Android.View.

  • 我怎样才能解决这类问题?问题在于setOnClickListener,它给了我一个NullPointerException。如果你还需要什么,请告诉我。 这是日志中的错误: