2013-09-26 3 views
0

Я внес некоторые изменения в свой код перед добавлением async-задачи, когда мое приложение корректно использует имя пользователя и пароль для аутентификации на удаленном сервере, но не может запустить другую активность при удалении имени входа в систему. Кто-то предлагает мне добавить async-задачу, теперь я добавил, но когда я ввожу правильное имя пользователя и пароль, его перестает работать. когда я ввожу неправильное имя пользователя и пароль, его правильное отображение неправильного имени пользователя. Если кто-нибудь сможет узнать, какие ошибки придут, пожалуйста, помогите мне.Не удалось запустить активность?

код-

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

} 
+1

Что написано в строке 41 вопроса QuestionActivity.java? –

+0

Возможно, опубликуйте весь метод 'processScreen'' QuestionActivty', если он не слишком большой, и укажите строку 41 – codeMagic

+0

@ZouZou currentGame = ((CYKApplication) getApplication()). GetCurrentGame(); –

ответ

1

Преобразование комментарии ответить

Глядя на LogCat мы можем видеть, что проблема заключается в строке 41 QuestionActivity. Поэтому мы знаем, что currentGame - null.

Вам необходимо установить контрольные точки до этого и посмотреть, что вызывает то, что должно быть null. Возможно, вы обнаружили, что другие переменные/объекты: null, что приводит к возникновению NPE.

+0

Мне нравится ваш ответ, а также повышайте его, потому что он помогает мне решить ошибку. Спасибо. –

+0

Мне нужна ваша еще одна помощь, если вы можете проверить эту ссылку. http://stackoverflow.com/questions/19054823/log-in-and-signup-page –

+0

@JohnR извините, я давно не был. Я постараюсь дать ему немного взглянуть, когда у меня будет шанс – codeMagic

0

Контекст неправильно, просто изменить:

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

к:

startActivity(new Intent(LoActivity.this, QuestionnActivity.class)); 
+0

'Context' в порядке. Согласно logcat, проблема заключается в 'QuestionActivity'. Кроме того, 'Context' в данном случае не дает« NPE ». – codeMagic

+0

Да, извините моя ошибка. – goodm

+0

его не работает, я уже пробовал этот код раньше. –

Смежные вопросы