小编典典

如何使用run runOnUithread?

java

我正在使用的应用程序具有登录/注册,该登录/注册连接到mysql数据库,起初我在上运行了所有程序,UI Thread后来发现由于无法在Android上运行长代码而无法运行UI Thread。我试图编辑我的代码以在Thread添加的新代码上运行长任务。。现在我的应用程序注册了,我在mysql中看到了结果,但是由于这个错误,我的应用程序一直关闭

android.view.ViewRootImpl$CalledFromWrongThreadException: 
Only the original thread that created a view hierarchy can touch its views.

该错误是可以理解的,但我不知道如何将Viewor或Views返回到UI Thread

我已经对进行了一些研究,runOnuithread但是我不知道将其放置在代码中的位置,或者天气我将Thread之前添加的新内容放置在错误的位置,所以请从头开始。

谁能帮我解决这个问题

这是代码片段

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) {
             /** According with the new StrictGuard policy,  running long tasks on the Main UI thread is not possible
            So creating new thread to create and execute http operations */
            new Thread (new Runnable() {
                @Override
                 public void run() {
            //
            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(), MainActivity.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();
            }
        }
            }).start();
        }
    });

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

阅读 603

收藏
2020-11-23

共1个答案

小编典典

由于您似乎将网络代码与代码混在一起UI,因此我不会尝试为您编写代码。我可以告诉您应该怎么做,并假设您可以自己重新排列代码,因为您知道代码的全部功能。

好吧,你的里面run(),你把你的网络代码,那么当你需要更新UI你可以有

runOnUiThread(new Runnable()
{
    @Override
    public void run()
    {
        // code to update UI
    }
});

话虽如此,我建议您将AsyncTask用于网络操作。这使它变得更加容易,因为它已经具有用于后台内容和更新的功能UI。您启动任务并doInBackground()运行,然后在这里执行所有网络操作。然后,您可以UI使用AsyncTasks其他3种方法中的任何一种更新。

2020-11-23