如何使用运行runOnUithread? [英] how to use run runOnUithread?

查看:128
本文介绍了如何使用运行runOnUithread?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该应用程序我的工作有一个登录/注册它连接到MySQL数据库,起初我跑上的所有 UI线程后来我才发现这是不工作,因为运行在Android的 UI线程长code中的反对。我试图编辑我的code运行在一个新的,我添加的长期任务。 。现在,我的应用程序注册了我看到的结果是在MySQL,但我的应用程序保持关闭,因为该错误

  android.view.ViewRootImpl $ CalledFromWrongThreadException:
只有创建一个视图层次可以触摸其观点原来的线程。
 

错误是可以理解的,但我不知道该怎么办好了查看查看发回给 UI线程

我已经做了一些研究 runOnuithread ,但我不知道在哪里把它放在我的code,或天气我把新的主题我在错误的地方之前添加到开始请

谁能帮我修复此

这里的code片段

 公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.register);

    //导入所有资产如按钮,文本字段
    inputFullName =(EditText上)findViewById(R.id.registerName);
    inputEmail =(EditText上)findViewById(R.id.registerEmail);
    控件inputPassword =(EditText上)findViewById(R.id.registerPassword);
    btnRegister =(按钮)findViewById(R.id.btnRegister);
    btnLinkToLogin =(按钮)findViewById(R.id.btnLinkToLoginScreen);
    registerErrorMsg =(TextView中)findViewById(R.id.register_error);

    //注册按钮点击事件
    btnRegister.setOnClickListener(新View.OnClickListener(){

        公共无效的onClick(视图查看){
             / **根据新StrictGuard政策,在主UI线程上运行的长期任务是不可能的
            因此,创建新的线程来创建和执行HTTP操作* /
            新主题(新的Runnable(){
                @覆盖
                 公共无效的run(){
            //
            字符串名称= inputFullName.getText()的toString()。
            。字符串email = inputEmail.getText()的toString();
            。字符串password = inputPassword.getText()的toString();
            UserFunctions userFunction =新UserFunctions();

            JSONObject的JSON = userFunction.registerUser(姓名,电子邮件,密码);

            //检查登录响应
            尝试 {
                //

                //
                如果(json.getString(KEY_SUCCESS)!= NULL){

                    registerErrorMsg.setText();
                    字符串解析度= json.getString(KEY_SUCCESS);
                    如果(的Integer.parseInt(RES)== 1){
                        //用户成功registred
                        在SQLite数据库//存储用户信息
                        数据库处理器DB =新的数据库处理器(getApplicationContext());
                        JSONObject的json_user = json.getJSONObject(用户);

                        在数据库//清除所有previous数据
                        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));
                        //启动仪表盘屏幕
                        仪表盘意图=新的意图(getApplicationContext(),MainActivity.class);
                        //关闭所有的观点发起仪表板前,
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(仪表盘);
                        //关闭注册画面
                        完();
                    }其他{
                        //登记错误
                        registerErrorMsg.setText(发生错误登记);
                    }
                } //
            }赶上(JSONException E){
                e.printStackTrace();
            }
        }
            })。开始();
        }
    });

    //链接登录屏幕
    btnLinkToLogin.setOnClickListener(新View.OnClickListener(){

        公共无效的onClick(视图查看){

            意图I =新的意图(getApplicationContext()
                    LoginActivity.class);
            startActivity(ⅰ);
            //关闭注册查看
            完();
        }
    });
}
}
 

解决方案

既然你似乎有网络code混合与 UI code,我又不是要尝试写吧。我可以告诉你应该如何,并假设你可以重新排列Ç自己的$ C $,因为你知道这一切呢。

好了,你的内运行()你把你的网络code,那么,当您需要更新 UI 可以有

  runOnUiThread(新的Runnable()
{
    @覆盖
    公共无效的run()
    {
        // code更新的用户界面
    }
});
 

随着中说,我建议使用 AsyncTask的为您的网络运营。这使得它更容易,因为它已经具有的功能为背景的东西,并更新 UI 。您启动任务和 doInBackground()运行,那就是,你做你的网络操作。然后你就可以在任何的 AsyncTasks 等3种方法更新 UI

使用的例子看到这个答案 的AsyncTask ,以及链接到上面的文档。

The app I am working on has a login/register which connects to a mysql database, At first I was running everything on the UI Thread I later found out it was not working because of the against running long code on Android's UI Thread. I attempted to edit my code to run the long task on a new Thread that i added. . Now my app registers the I see the result in mysql but my app keeps closing because of this error

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

the error is understandable but I don't know how to run the View or Views back to the UI Thread.

I've done some research about the runOnuithread but I dont know where to place it in my code, or weather I placed the new Thread I added before in the wrong place to begin with please

can anyone help my fix this

here is a snippet of the code

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

解决方案

Since you seem to have network code mixed in with UI code, I'm not going to try and write it for you. I can tell you how it should be and assume that you can rearrange the code yourself since you know what all of it does.

Ok, inside your run() you put your network code then when you need to update the UI you can have

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

With that said, I recommend using AsyncTask for your network operations. This makes it much easier as it already has the functions for background stuff and updating the UI. You start the task and doInBackground() runs and that is where you do all of your network operations. Then you can update the UI in any of AsyncTasks other 3 methods.

See this answer for an example of using AsyncTask, along with the link to the docs above.

这篇关于如何使用运行runOnUithread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆