0

我们正在制作一个具有登录功能和存储在服务器上的 mySQL 数据库的 Android 应用程序。我找到了一段代码,让它在低于 API 级别 3.0 的 Android 设备上正常工作。除此之外的任何事情都会崩溃。我被告知使用 Asynctask 来解决我的问题。要将 UI 代码与网络代码分开?被告知应该很容易,但我不知道如何让它工作。谁能告诉我我需要做什么才能使这段代码正常工作?我花了无数个小时研究这个问题,但仍然没有运气。我很感激任何帮助。谢谢

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)
4

2 回答 2

1

从 ICS 及以上版本 Android 将不允许在 UI 线程中进行任何网络操作。它应该在单独的线程中完成,这样它就不会挂起 UI。在单独的线程中尝试您的网络通信代码。

请参阅此链接。它解释了为什么会在 Android 3.0 及更高版本上发生这种情况。

于 2013-01-16T05:07:02.753 回答
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
    }
}
于 2013-01-16T05:18:53.363 回答