2012-08-16 50 views
0

我在android 3.1上運行,我在我的登錄java類中實現了異步。但是,在我實現它之後,我得到了嚴格的模式異常。爲什麼會出現這種錯誤?爲什麼在執行異步任務後仍然存在網絡空例外?

Login.java

public class LoginActivity extends Activity { 
Button btnLogin; 
Button btnLinkToRegister; 
EditText inputNric; 
EditText inputPassword; 
TextView loginErrorMsg; 


// Progress Dialog 
private ProgressDialog pDialog; 

// JSON Response node names 
//success is the column name of the database - KEY_SUCCESS is we create the name 
private static String KEY_SUCCESS = "success"; 
private static String KEY_ERROR = "error"; 
private static String KEY_ERROR_MSG = "error_msg"; 
private static String KEY_NAME = "name"; 
private static String KEY_NRIC = "nric"; 
private static String KEY_CREATED_AT = "created_at"; 

    @Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.login); 

    //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    // StrictMode.setThreadPolicy(policy); 

    // Importing all assets like buttons, text fields 
    inputNric = (EditText) findViewById(R.id.loginNric); 
    inputPassword = (EditText) findViewById(R.id.loginPassword); 
    btnLogin = (Button) findViewById(R.id.buttonLogin); 
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen); 
    loginErrorMsg = (TextView) findViewById(R.id.login_error); 

    // login button click event 
    btnLogin.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View arg0) { 
      // starting background task to update case 
      new LoginUser().execute(); 
     } 
    }); 

    /*// Link to Register Screen 
    btnLinkToRegister.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      Intent i = new Intent(getApplicationContext(), 
      RegisterActivity.class); 
      startActivity(i); 
      finish(); 
     } 
    });*/ 
} 

/** 
* Background Async Task to Login User 
* */ 
    class LoginUser extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */   
     protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(LoginActivity.this); 
     pDialog.setMessage("Logging In ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
     } 

     /** 
     * Logging in 
     * */ 
     protected String doInBackground(String... params) { 
      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
       String nric = inputNric.getText().toString(); 
       String password = inputPassword.getText().toString(); 
       UserFunctions userFunction = new UserFunctions(); 
       Log.d("Button", "Login"); 
       JSONObject json = userFunction.loginUser(nric, password); 

       // check for login response 
       try { 
        if (json.getString(KEY_SUCCESS) != null) { 
         loginErrorMsg.setText(""); 
         String res = json.getString(KEY_SUCCESS); 
         if(Integer.parseInt(res) == 1){ 
          // user successfully logged in 
          // Store user details in SQLite Database 
          DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 
          JSONObject json_user = json.getJSONObject("user"); 

          // Clear all previous data in database 
          userFunction.logoutUser(getApplicationContext()); 
          db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_NRIC), json_user.getString(KEY_CREATED_AT));      

          // Launch home Screen 
          Intent home = new Intent(getApplicationContext(), AllTabActivity.class); 

          // Close all views before launching home 
          home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
          startActivity(home); 

          // Close Login Screen 
          finish(); 
         }else{ 
          // Error in login 
          loginErrorMsg.setText("Incorrect username/password"); 
         } 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
       } 
      }); 
       return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once case deleted 
      pDialog.dismiss(); 

     } 
    } 

    } 

logcat的錯誤:

08-14 17:46:37.766: E/AndroidRuntime(1208): android.os.NetworkOnMainThreadException 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at java.net.InetAddress.lookupHostByName(InetAddress.java:477) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at java.net.InetAddress.getAllByName(InetAddress.java:249) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at com.pivestigator.JSONParser.makeHttpRequest(JSONParser.java:51) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at com.pivestigator.login.library.UserFunctions.loginUser(UserFunctions.java:40) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at com.pivestigator.login.LoginActivity$LoginUser$1.run(LoginActivity.java:112) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at android.os.Handler.handleCallback(Handler.java:587) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at android.os.Handler.dispatchMessage(Handler.java:92) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at android.os.Looper.loop(Looper.java:132) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at android.app.ActivityThread.main(ActivityThread.java:4025) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at java.lang.reflect.Method.invokeNative(Native Method) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at java.lang.reflect.Method.invoke(Method.java:491) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 
08-14 17:46:37.766: E/AndroidRuntime(1208):  at dalvik.system.NativeStart.main(Native Method) 

回答

0

您已經runOnUiThread做網絡業務,這將被調入事件線程,而不是你應該做如下:

/** 
* Background Async Task to Login User 
* */ 
    class LoginUser extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */   
     protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(LoginActivity.this); 
     pDialog.setMessage("Logging In ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
     } 

     /** 
     * Logging in 
     * */ 
     protected String doInBackground(String... params) { 
      // updating UI from Background Thread 
       String nric = inputNric.getText().toString(); 
       String password = inputPassword.getText().toString(); 
       UserFunctions userFunction = new UserFunctions(); 
       Log.d("Button", "Login"); 
       JSONObject json = userFunction.loginUser(nric, password); 

       // check for login response 
       try { 
        if (json.getString(KEY_SUCCESS) != null) { 
         loginErrorMsg.setText(""); 
         String res = json.getString(KEY_SUCCESS); 
         if(Integer.parseInt(res) == 1){ 
          // user successfully logged in 
          // Store user details in SQLite Database 
          DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 
          JSONObject json_user = json.getJSONObject("user"); 

          // Clear all previous data in database 
          userFunction.logoutUser(getApplicationContext()); 
          db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_NRIC), json_user.getString(KEY_CREATED_AT));      

runOnUiThread(new Runnable() { 
      public void run() { 

          // Launch home Screen 
          Intent home = new Intent(getApplicationContext(), AllTabActivity.class); 

          // Close all views before launching home 
          home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
          startActivity(home); 

          // Close Login Screen 
          finish(); 
         }else{ 
          // Error in login 
          loginErrorMsg.setText("Incorrect username/password"); 
         } 
} 
}); 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

       return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once case deleted 
      pDialog.dismiss(); 

     } 
    } 

    } 
+0

哦。我也嘗試過這種方式,但給出了大量的錯誤。看到這裏 - > http://stackoverflow.com/questions/11965046/error-implementing-async-task-in-this-class – Twister 2012-08-16 05:54:29

+0

檢查你還沒有實施的代碼,我後來編輯。 – jeet 2012-08-16 06:05:14

+0

else語法錯誤標記和'} catch(JSONException e)'括號上的語法錯誤。 – Twister 2012-08-16 06:18:46

相關問題