0

I have made some changes in my code before adding async task my app working proper its authenticate username and password from remote server but unable to launch other activity when login successful message disappear. Some one suggest me to add async task now i have added that but when i enter correct username and password its stop working. when i enter wrong username and password its working proper show wrong username password message. If anyone able to know what errors coming please help me.

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();
            }
        }
    }
}  

Log cat-

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;
        }

}
John R
  • 2,078
  • 8
  • 35
  • 58
  • 1
    What is wrote on the line 41 of QuestionActivity.java ? – Alexis C. Sep 26 '13 at 14:46
  • Maybe post the whole `processScreen` method of `QuestionActivty` if it isn't too big and indicate line 41 – codeMagic Sep 26 '13 at 14:49
  • @ZouZou currentGame = ((CYKApplication)getApplication()).getCurrentGame(); – John R Sep 26 '13 at 15:01
  • @codeMagic hi you and raghunadan advise me tomorrow to use asynctask. thank you for that. – John R Sep 26 '13 at 15:03
  • Yes, I remember it, *yesterday*. But it seems your `AsyncTask` is fine. The problem is in your `QuestionActivity`. So we need to see what is at line 41 of that `Activity`. – codeMagic Sep 26 '13 at 15:07
  • @JohnR which is line 41? – codeMagic Sep 26 '13 at 15:12
  • currentQ = currentGame.getNextQuestion(); – John R Sep 26 '13 at 15:14
  • Then `currentGame ` is `null`. I don't know what you are doing there but you will have to find out why that would be `null`. – codeMagic Sep 26 '13 at 15:16
  • Here's full code. please help me. – John R Sep 26 '13 at 15:20
  • @codeMagic i have added @SuppressLint("NewApi") at some places in async task to solve errors before. is that creating any problem? – John R Sep 26 '13 at 15:26
  • It could but I don't think it is causing the problem here. You have to debug and see why that would be `null`. We know that `currentGame` is `null` so that means that it isn't getting initialized properly. Put a breakpoint where you initialize it and see what is happening there. Check the values of things that are initializing it. – codeMagic Sep 26 '13 at 15:38
  • Before adding async task everything fine but now its not. – John R Sep 26 '13 at 15:46
  • @JohnR asynctask has nothing to do with NPE. you are getting NPE so check `getCurrentGame()` returns the right value – Raghunandan Sep 26 '13 at 16:30
  • I debug my app when i debug line 41 its show ***The method getCurrentGame() is undefined for the type QuestionActivity*** but before adding async task my app works fine. i never face this error before. please help me to solve this error. – John R Sep 27 '13 at 08:28
  • @codeMagic can you send me your debug comment as a answer i want to select that as a answer bcoz its solved my problem. Thank you. – John R Sep 27 '13 at 11:59
  • @JohnR `getCurrentGame()` undefined for the type QuestionActivity means you do not have a method with that name in your QuestionActivity – Raghunandan Sep 27 '13 at 12:10
  • @JohnR pls leave a comment on the relevant question. Also what is the difficult. post your updated code – Raghunandan Sep 27 '13 at 12:14
  • @Raghunandan In this code i am calling other activity in Move_to_next() method instead of correct activity. Now i replace QuestionActivity with correct activity its working fine. – John R Sep 27 '13 at 12:27
  • sorry i know this is my mistake. thank you all for your help. – John R Sep 27 '13 at 12:29
  • @JohnR could not reply in time was busy with some other work. glad you could figure out yourself. – Raghunandan Sep 27 '13 at 12:44
  • @Raghunandan I added new sign up button in xml and want that if user is not registered he click on that to register and this data stored in my remote database but i dont how to write code for that in this class.. i am very glad if you help me. – John R Sep 27 '13 at 12:46
  • @JohnR post a new question – Raghunandan Sep 27 '13 at 12:47

2 Answers2

1

Converting comments to answer

By looking at the logcat we can see that the problem is at line 41 of QuestionActivity. So we know that currentGame is null.

You need to set breakpoints before that and see what is causing that to be null. You may have found that other variables/objects arenull which ends up causing the NPE.

codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • I like your answer as well upvote it because it helps me to solve error. thank you. – John R Sep 28 '13 at 07:32
  • i need your one more help if you can please check this link. http://stackoverflow.com/questions/19054823/log-in-and-signup-page – John R Sep 28 '13 at 07:35
  • @JohnR sorry, I've been away for awhile. I will try to give it a look in a little while when I have a chance – codeMagic Sep 29 '13 at 00:09
  • http://stackoverflow.com/questions/19065613/unable-to-convert-this-login-page-to-signup-page i think this question elaborate my problem completly. – John R Sep 30 '13 at 07:51
  • hi how r you? please check this link http://stackoverflow.com/questions/19272345/how-to-start-new-countdowntimer-in-dialog-box-with-remaining-seconds/19272536?noredirect=1#comment28533755_19272536 – John R Oct 09 '13 at 13:14
  • sorry this one. http://stackoverflow.com/questions/19272345/how-to-start-new-countdowntimer-in-dialog-box-with-remaining-seconds – John R Oct 09 '13 at 13:43
  • hi I need your little help. – John R Feb 16 '14 at 05:45
  • I need a lot of help. What's the problem? Have you posted a question? – codeMagic Feb 16 '14 at 05:47
  • or http://stackoverflow.com/questions/21694306/how-to-set-text-size-in-webview-in-android/21821192?noredirect=1#21821192 – John R Feb 17 '14 at 08:11
0

Context is wrong, just change:

startActivity(new Intent(this, QuestionnActivity.class));

to:

startActivity(new Intent(LoActivity.this, QuestionnActivity.class));
goodm
  • 7,275
  • 6
  • 31
  • 55