2013-01-16 77 views
0

我們正在製作一個Android應用程序,它具有存儲在服務器上的登錄功能和mySQL數據庫。我找到了一段代碼,並在Android設備低於API級別3.0的情況下正常工作。除此之外的任何東西都會崩潰。我被告知使用Asynctask來解決我的問題。從網絡代碼分離UI代碼?被告知它應該很容易,但我不知道如何讓它工作。任何人都應該正確地知道我需要做什麼來使這個代碼工作?我花了數小時研究這個問題,仍然沒有運氣。我感謝任何幫助。謝謝如何修改此代碼以使其適用於Android API 3.0?

public class RegisterActivity extends Activity { 
Button btnRegister; 
Button btnLinkToLogin; 
EditText inputFullName; 
EditText inputEmail; 
EditText inputPassword; 
TextView registerErrorMsg; 

// JSON Response node names 
private static String KEY_SUCCESS = "success"; 
private static String KEY_ERROR = "error"; 
private static String KEY_ERROR_MSG = "error_msg"; 
private static String KEY_UID = "uid"; 
private static String KEY_NAME = "name"; 
private static String KEY_EMAIL = "email"; 
private static String KEY_CREATED_AT = "created_at"; 

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

    // Importing all assets like buttons, text fields 
    inputFullName = (EditText) findViewById(R.id.registerName); 
    inputEmail = (EditText) findViewById(R.id.registerEmail); 
    inputPassword = (EditText) findViewById(R.id.registerPassword); 
    btnRegister = (Button) findViewById(R.id.btnRegister); 
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); 
    registerErrorMsg = (TextView) findViewById(R.id.register_error); 

    // Register Button Click event 
    btnRegister.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 
      String name = inputFullName.getText().toString(); 
      String email = inputEmail.getText().toString(); 
      String password = inputPassword.getText().toString(); 
      UserFunctions userFunction = new UserFunctions(); 
      JSONObject json = userFunction.registerUser(name, email, password); 

      // check for login response 
      try { 
       if (json.getString(KEY_SUCCESS) != null) { 
        registerErrorMsg.setText(""); 
        String res = json.getString(KEY_SUCCESS); 
        if(Integer.parseInt(res) == 1){ 
         // user successfully registred 
         // 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_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT)); 
         // Launch Dashboard Screen 
         Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class); 
         // Close all views before launching Dashboard 
         dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         startActivity(dashboard); 
         // Close Registration Screen 
         finish(); 
        }else{ 
         // Error in registration 
         registerErrorMsg.setText("Error occured in registration"); 
        } 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 

    // Link to Login Screen 
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() { 

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

這裏也是logCatError

D/AndroidRuntime(10040): Shutting down VM 
W/dalvikvm(10040): threadid=1: thread exiting with uncaught exception (group=0x416f2930) 
E/AndroidRuntime(10040): FATAL EXCEPTION: main 
E/AndroidRuntime(10040): android.os.NetworkOnMainThreadException 
E/AndroidRuntime(10040): at  android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 
E/AndroidRuntime(10040): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 
E/AndroidRuntime(10040): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 
E/AndroidRuntime(10040): at libcore.io.IoBridge.connect(IoBridge.java:112) 
E/AndroidRuntime(10040): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 
E/AndroidRuntime(10040): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 
E/AndroidRuntime(10040): at java.net.Socket.connect(Socket.java:842) 
+0

看到此鏈接http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception –

回答

1

從ICS及以上版本的Android將不允許在UI thread.It任何網絡操作應在單獨的線程來完成,因此深得掛起UI。在單獨的線程中嘗試您的網絡通信代碼。

請參閱Link。它解釋了爲什麼會出現在Android 3.0及更高版本上。

+0

+1尼斯答案.. –

0

確實,android已經對UI線程變得非常嚴格,並且不會允許您在UI線程上執行後臺計算,因爲它會降低性能。您被告知正確使用異步任務來執行網絡通信。你可以通過使用new yourTask().execute();在你的註冊按鈕的onCLick上執行asyncTask來完成。

然後寫一個類的AsyncTask這樣

private class yourTask extends AsyncTask<Integer, Void, Integer> { 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     //show a progress bar 
    } 

    @Override 
    protected String doInBackground(Integer... params) { 
     // your network communication code will be here. 
     return 0; 
    }  

    @Override 
    protected void onPostExecute(Integer result) { 
     super.onPostExecute(result); 
     //show the result here 
    } 
} 
相關問題