使用异步任务 [英] Using AsyncTask

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

问题描述

抱歉,如果这是一个简单的问题,但我对此很陌生并且仍在学习.

Apologies if this is a simple question but I am very new to this and still learning.

我有一个应用程序,当我的用户在输入他们的详细信息后单击按钮登录时,它因 android.os.NetworkOnMainThreadException 而崩溃我发现这是因为我在主线程上执行网络操作并解决我需要使用 AsyncTask,但是我被语法困住了.

I have an app and when my users click the button to login after entering their details, it is crashing with android.os.NetworkOnMainThreadException I have discovered this is because I am performing a network operation on the main thread and to resolve I need to use AsyncTask, I am stuck however with the syntax.

这是我点击按钮后的代码,调用一个函数进行连接,然后将json解析为sqlite db.

Here is my code after the button is clicked, calls a function to connect and then parses json into sqlite db.

// Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();
            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.loginUser(email, 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_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 Login Screen
                        finish();
                    }else{
                        // Error in login
                        loginErrorMsg.setText("Incorrect username/password");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

如何将其更改为正确的类?我没有传递 URL 等.我认为它需要是这样的,但我真的很难获得正确的语法.

How do I change this to the correct class ? I am not passing URL's etc. I think it needs to be something like this , but I am really struggling to get the syntax right.

非常感谢!!!

class login extends AsyncTask<Void, Void, Void> {

    private Exception exception;

    protected ??? doInBackground(???) {
        try {

推荐答案

应该是这样的

   public class TalkToServer extends AsyncTask<Void, Void, Void> {

   @Override
   protected void onPreExecute() {
        /*
         *    do things before doInBackground() code runs
         *    such as preparing and showing a Dialog or ProgressBar
        */
   }

   @Override
   protected void onProgressUpdate(Void... values) {
        /*
         *    updating data
         *    such a Dialog or ProgressBar
        */

   }

   @Override
   protected Void doInBackground(Void... params) {
      //do your work here
      return null;
   }

   @Override
   protected void onPostExecute(Void result) {
        /*
         *    do something with data here
         *    display it or send to mainactivity
         *    close any dialogs/ProgressBars/etc...
        */
   }
}

然后你可以执行它

TalkToServer myTask = new MyTask(); // can add params for a constructor if needed
myTask.execute(); // here is where you would pass data to doInBackground()

如果您不使用 onProgressUpdate()onPreExecute() 来显示 Dialog、进度或doInBackground() 之前或期间的其他任务.

You may not need onProgressUpdate() or onPreExecute() if you aren't using them to show a Dialog, progress, or other tasks before or during doInBackground().

onPreExecute() 可用于初始化和显示 ProgressDialog.然后它可以在 onPostExecute()

onPreExecute() can be used to initialize and show a ProgressDialog. Then it could be dismissed in onPostExecute()

任务完成后

onPostExecute() 将被调用.如果该类是您的 Activity 的内部类,那么您可以在那里更新 UI 元素或在任务完成后调用函数来运行代码.如果它是一个与 Activity 不同的文件,那么您可以使用 interface 并为 Activity 创建一个 callBack并在任务完成后在那里运行代码.

onPostExecute() will be called. If the class is an inner-class of your Activity then you can update UI elements there or call a function to run code once the task finishes. If it is a separate file than the Activity then you can use an interface and create a callBack to the Activity and run code there once the task finishes.

这个答案谈到使用接口进行回调,如果你需要

确保在除doInBackground()之外的任何方法中完成任何UI更新,或者在除之外的任何函数中将任何UI更新发送回Activity>doInBackground().网络操作等繁重的工作应该在doInBackground()中完成.

Make sure any UI updating is done in any method besides doInBackground() or sent back to the Activity in any function besides doInBackground(). Heavy-lifting such as network operations should be done in doInBackground().

另外,请务必通读AsyncTask 文档.尤其是线程规则

Also, be sure to read through the AsyncTask Docs completely. Especially the Threading Rules

这篇关于使用异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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