无法启动活动?

2024-05-18

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

Code-

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

问题活动-

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。所以我们知道currentGame is null.

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法启动活动? 的相关文章

  • 斯坦福 NLP - 处理文件列表时 OpenIE 内存不足

    我正在尝试使用斯坦福 CoreNLP 中的 OpenIE 工具从多个文件中提取信息 当多个文件 而不是一个 传递到输入时 它会给出内存不足错误 All files have been queued awaiting termination
  • 如何在PreferenceActivity中添加工具栏

    我已经使用首选项创建了应用程序设置 但我注意到 我的 PreferenceActivity 中没有工具栏 如何将工具栏添加到我的 PreferenceActivity 中 My code 我的 pref xml
  • 在 SQLite 中搜索时排除 HTML 标签和一些 UNICODE 字符

    更新 4 我已经成功运行了firstchar例如 但现在的问题是使用regex 即使包含头文件 它也无法识别regex操作员 有什么线索可以解决这个问题吗 更新 2 我已经编译了sqlite3我的项目中的库 我现在正在寻找任何人帮助我为我的
  • Google 云端硬盘身份验证异常 - 需要许可吗? (v2)

    我一直在尝试将 Google Drive v2 添加到我的 Android 应用程序中 但无法获得授权 我收到 UserRecoverableAuthIOException 并显示消息 NeedPermission 我感觉 Google A
  • 从 127.0.0.1 到 2130706433,然后再返回

    使用标准 Java 库 从 IPV4 地址的点分字符串表示形式获取的最快方法是什么 127 0 0 1 到等效的整数表示 2130706433 相应地 反转所述操作的最快方法是什么 从整数开始2130706433到字符串表示形式 127 0
  • Java按日期升序对列表对象进行排序[重复]

    这个问题在这里已经有答案了 我想按一个参数对对象列表进行排序 其日期格式为 YYYY MM DD HH mm 按升序排列 我找不到正确的解决方案 在 python 中使用 lambda 很容易对其进行排序 但在 Java 中我遇到了问题 f
  • 如何发布Android .aar源以使Android Studio自动找到它们?

    我正在将库发布到内部 Sonatype Nexus 存储库 Android Studio 有一个功能 可以自动查找通过 gradle 引用的库的正确源 我将 aar 的源代码作为单独的 jar 发布到 Nexus 但 Android Stu
  • Android Studio 0.4.3 Eclipse项目没有gradle

    在此版本之前 在 Android Studio 中按原样打开 Eclipse 项目似乎很容易 无需任何转换 我更喜欢 Android Studio 环境 但我正在开发一个使用 eclipse 作为主要 IDE 的项目 我不想只为这个项目下载
  • 使用Caliper时如何指定命令行?

    我发现 Google 的微型基准测试项目 Caliper 非常有趣 但文档仍然 除了一些示例 完全不存在 我有两种不同的情况 需要影响 JVM Caliper 启动的命令行 我需要设置一些固定 最好在几个固定值之间交替 D 参数 我需要指定
  • 总是使用 Final?

    我读过 将某些东西做成最终的 然后在循环中使用它会带来更好的性能 但这对一切都有好处吗 我有很多地方没有循环 但我将 Final 添加到局部变量中 它会使速度变慢还是仍然很好 还有一些地方我有一个全局变量final 例如android Pa
  • 如何在控制器、服务和存储库模式中使用 DTO

    我正在遵循控制器 服务和存储库模式 我只是想知道 DTO 在哪里出现 控制器应该只接收 DTO 吗 我的理解是您不希望外界了解底层域模型 从领域模型到 DTO 的转换应该发生在控制器层还是服务层 在今天使用 Spring MVC 和交互式
  • Android访问远程SQL数据库

    我可以直接从 Android 程序访问远程 SQL 数据库 在网络服务器上 吗 即简单地打开包含所有必需参数的连接 然后执行 SQL 查询 这是一个私人程序 不对公众开放 仅在指定的手机上可用 因此我不担心第三方获得数据库访问权限 如果是这
  • 仅将 char[] 的一部分复制到 String 中

    我有一个数组 char ch 我的问题如下 如何将 ch 2 到 ch 7 的值合并到字符串中 我想在不循环 char 数组的情况下实现这一点 有什么建议么 感谢您花时间回答我的问题 Use new String value offset
  • 无法捆绑适用于 Mac 的 Java 应用程序 1.8

    我正在尝试将我的 Java 应用程序导出到 Mac 该应用程序基于编译器合规级别 1 7 我尝试了不同的方法来捆绑应用程序 1 日食 我可以用来在 Eclipse 上导出的最新 JVM 版本是 1 6 2 马文 看来Maven上也存在同样的
  • 获取 JVM 上所有引导类的列表?

    有一种方法叫做findBootstrapClass对于一个类加载器 如果它是引导的 则返回一个类 有没有办法找到类已经加载了 您可以尝试首先通过例如获取引导类加载器呼叫 ClassLoader bootstrapLoader ClassLo
  • 编译器抱怨“缺少返回语句”,即使不可能达到缺少返回语句的条件

    在下面的方法中 编译器抱怨缺少退货声明即使该方法只有一条路径 并且它包含一个return陈述 抑制错误需要另一个return陈述 public int foo if true return 5 鉴于Java编译器可以识别无限循环 https
  • 如何在Xamarin中删除ViewTreeObserver?

    假设我需要获取并设置视图的高度 在 Android 中 众所周知 只有在绘制视图之后才能获取视图高度 如果您使用 Java 有很多答案 最著名的方法之一如下 取自这个答案 https stackoverflow com a 24035591
  • 有没有办法为Java的字符集名称添加别名

    我收到一个异常 埋藏在第 3 方库中 消息如下 java io UnsupportedEncodingException BIG 5 我认为发生这种情况是因为 Java 没有定义这个名称java nio charset Charset Ch
  • android sdk 的位置尚未在 Windows 操作系统的首选项中设置

    在 Eclipse 上 我转到 windows gt Android SDK 和 AVD Manager 然后弹出此消息 Android sdk 的位置尚未在首选项中设置 进入首选项 在侧边栏找到 Android 然后会出现一个 SDK 位
  • 节拍匹配算法

    我最近开始尝试创建一个移动应用程序 iOS Android 它将自动击败比赛 http en wikipedia org wiki Beatmatching http en wikipedia org wiki Beatmatching 两

随机推荐