当前位置: 首页 > 知识库问答 >
问题:

AsyncTask已完成[重复]

朱梓
2023-03-14
@Override
public void onRefresh() {
    if (!AlertView.isInternetAvailable(getContext())) {
        swipeLayout.setRefreshing(false);
        Toast.makeText(getContext(), Messages.CONNECTION_ERROR + ": " + Messages.NO_INTERNET, Toast.LENGTH_SHORT).show();
    } else {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new UpdateProfile(getActivity(), swipeLayout, sharedPreferences.getString(Constants.TOKEN, ""), user.getIin()).execute(Urls.GET_USER);
            }
        });
        profileDefaults();
    }
}

这里是我的AsyncTask方法:

public class UpdateProfile extends AsyncTask <String, Void, String> {
private Activity activity;
private SwipeRefreshLayout swipeRefreshLayout;
private String token;
private String userIin;
private SharedPreferences sharedPreferences;

public UpdateProfile(Activity activity, SwipeRefreshLayout swipeRefreshLayout, String token, String userIin) {
    this.activity = activity;
    this.swipeRefreshLayout = swipeRefreshLayout;
    this.token = token;
    this.userIin = userIin;
    sharedPreferences = this.activity.getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);
}

@Override
protected String doInBackground(String... params) {
    URL url = null;
    try {
        url = new URL(params[0]);
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("iin", userIin)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .addHeader(Constants.AUTH_TOKEN, token)
                    .post(body)
                    .build();
            Response responses = null;
            try {
                responses = okHttpClient.newCall(request).execute();
            } catch (Exception e) {
                AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
            }

            assert responses != null;
            return responses.body().string();

        } catch (Exception e) {
            AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
        }
    } catch (Exception e) {
        AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    try {
        JSONObject jsonObject = new JSONObject(s);
        int code = Integer.valueOf(jsonObject.getString(Constants.CODE));
        if (code == Codes.OK) {
            Toast.makeText(activity, "Данные обновлены", Toast.LENGTH_SHORT).show();

            String userHeader = jsonObject.getString("user");
            JSONObject userInfo = new JSONObject(userHeader);

            String mobilePhone = userInfo.getString(SingletonConstants.MOBILE_PHONE);
            Boolean isActive = userInfo.getBoolean(SingletonConstants.IS_ACTIVE);
            Boolean signedAgreement = userInfo.getBoolean(SingletonConstants.SIGNED_AGREEMENT);
            Boolean esfEntered = userInfo.getBoolean(SingletonConstants.ESF_ENTERED);
            String address = userInfo.getString(SingletonConstants.ADDRESS);
            String iin = userInfo.getString(SingletonConstants.IIN);
            String certExpDate = userInfo.getString(SingletonConstants.CERT_EXP_DATE);
            String firstName = userInfo.getString(SingletonConstants.FIRST_NAME);
            String middleName = userInfo.getString(SingletonConstants.MIDDLE_NAME);
            String workPhone = userInfo.getString(SingletonConstants.WORK_PHONE);
            String secondName = userInfo.getString(SingletonConstants.SECOND_NAME);
            String avatarUrl = userInfo.getString(SingletonConstants.AVATAR_URL);;
            String secondEmail = userInfo.getString(SingletonConstants.SECOND_EMAIL);
            String email = userInfo.getString(SingletonConstants.EMAIL);

            User newUser = new User(mobilePhone, isActive, signedAgreement, esfEntered, address, iin, certExpDate, firstName, middleName, workPhone, secondName, avatarUrl, secondEmail, email);

            Gson gson = new Gson ();
            String userGson = gson.toJson (newUser);
            sharedPreferences.edit().putString(SingletonConstants.USER, userGson).apply();
            swipeRefreshLayout.setRefreshing(false);

        } else {
            AlertView.showAlertView(activity, Messages.ERROR, jsonObject.getString(Constants.MESSAGE), Messages.OK);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

如何调用profileDefaults()?是我的活动。我需要在OnPostExecute之后调用它!

共有1个答案

张光辉
2023-03-14

一种更干净的方法是使用接口作为侦听器。创建此接口:

public interface OnAsyncFinished{
    void onAsyncFinished(Object o);
}

将接口作为参数添加到AsyncTaskClass构造函数中:

private OnAsyncFinished onAsyncFinished;
public UpdateProfile(..., OnAsyncFinished onAsyncFinished) {
   ...
   this.onAsyncFinished = onAsyncFinished;
}
...
@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    onAsyncFinished.onAsyncFinished(s); //This will notifiy the method on main activity, and you can now resume the work there
    ...
}

在您的主要活动中实现接口:

public MainActivity extends Activity implements OnAsyncFinished {
     @Override
     public void onAsyncFinished(Object o) {
         //This will get called after onPostExecute, do what u want with the object you got from onPostExecute, json or string in ur example
         profileDefaults(); //call ur function
     }
}
        @Override
        public void run() {
            new UpdateProfile(..., this).execute(Urls.GET_USER);
        }
 类似资料:
  • 问题内容: 我通过将操作拆分为可用的确切内核数来并行化操作,然后通过启动相同数量的AsyncTask,对数据的不同部分执行相同的操作。 我正在使用以并行化它们的执行。 我想知道每个线程何时完成其工作,以便结合所有结果并执行进一步的操作。 我能怎么做? 问题答案: 您还可以简单地将共享库中的计数器递减作为的一部分。由于在同一线程(主线程)上运行,因此您不必担心同步。 更新1 共享对象可能看起来像这样

  • 根据Espresso文档,检测测试应该自动等待完成。但它不起作用。我创建了这个简单的测试用例: 返回UI线程时测试应该失败,但它总是成功。这是测试的logcat输出: 正如您所看到的,测试在后台方法执行之前就已经完成了。我怎样才能让考试等待呢?

  • 错误:------崩溃开始 08-04 05:53:11.807 266 7-2667/com.example.kwei.minigame1 E/AndroidRuntime:致命异常:main process:com.example.kwei.minigame1,PID:2667 java.lang.nullpointerException:试图在com.example.kwei.minigam

  • 问题内容: 由于某种原因,我完成后没有被调用。 我的班级干事: 我的onPostExecute(): 一切正常,我成功完成并返回一个布尔值,但随后就结束了。 谢谢 问题答案: 您是否在UI线程上创建了AsyncTask?还要在onPostExecute()方法上添加一个@Override注释,以确保正确声明了它。