Загрузка данных о пользователе в Async Task через API Appwrite
Хочу как-то переформатировать код в Async Task чтобы сначала данные загружались с облака Appwrite, а уже после этого они высвечивались в виджетах. Дело в том, что код снизу выполняет задачу, но если пользователь будет постоянно тыкать на профиль, то приложение вылетит. Да и вообще, такие вещи нужно оформлять через Async Task.
Я пытался сделать это с помощью AsyncTask самостоятельно, разделив части на doInBackground()
и onPostExecute()
. Но почему-то данные не загружались в виджеты. В идеале чтобы ответ был с объяснением.
Вот код который без AsyncTask
String masterKeyAlias = null;
try {
masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
SharedPreferences sharedPreferences = null;
try {
sharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
getContext(),
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
String loggedStatus = sharedPreferences.getString("savedStatus", "");
String loggedEmail = sharedPreferences.getString("savedEmail", "");
String loggedPassword = sharedPreferences.getString("savedPassword", "");
String loggedSessionId = sharedPreferences.getString("savedSessionId", "");
String loggedUsername = sharedPreferences.getString("savedUsername", "");
String loggedCreateData = sharedPreferences.getString("savedCreateData", "");
String loggedMainInfo = sharedPreferences.getString("savedMainInfo", "");
String loggedSessionCreateData = sharedPreferences.getString("savedSessionCreateData", "");
String loggedAvatarBase64String = sharedPreferences.getString("savedAvatar", "");
SharedPreferences.Editor editor = sharedPreferences.edit();
Client client = new Client(getContext())
.setEndpoint("api_endpoint_link") // Your API Endpoint
.setProject("project_id"); // Your project ID
Account account = new Account(client);
if (!(loggedStatus.startsWith("true"))) {
RelativeLayout profileInfoLayout = getView().findViewById(R.id.profileInfoLayout);
profileInfoLayout.setVisibility(View.GONE);
}
if (loggedStatus.startsWith("true")) {
account.getSession(
loggedSessionId,
new Continuation<Object>() {
@NotNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resumeWith(@NotNull Object o) {
try {
if (o instanceof Result.Failure) {
Result.Failure failure = (Result.Failure) o;
throw failure.exception;
} else {
io.appwrite.models.Session currentSession = (Session) o;
String sessionStatus = "true";
currentSessionString = currentSession.getId();
}
} catch (AppwriteException appwriteException) {
editor.clear();
editor.putString("savedStatus", "false");
editor.apply();
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(ProfileFragment.this.getContext().getApplicationContext(), getResources().getString(R.string.wrongSessionId), Toast.LENGTH_LONG);
toast.show();
}
});
} catch (Throwable th) {
Log.e("ERROR", th.toString());
}
}
});
account.get(new Continuation<Object>() {
@NotNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resumeWith(@NotNull Object o) {
try {
if (o instanceof Result.Failure) {
Result.Failure failure = (Result.Failure) o;
try {
throw failure.exception;
} catch (Throwable e) {
throw new RuntimeException(e);
}
} else {
io.appwrite.models.Account currentAccount = (io.appwrite.models.Account) o;
String currentUsername = (String) ((io.appwrite.models.Account) o).getName();
String currentCreateData = (String) currentAccount.getCreatedAt();
Preferences currentAccountPrefs = (Preferences) currentAccount.getPrefs();
String currentMainInfoString = (String) currentAccountPrefs.getData().getOrDefault("main_info", "nope");
String currentAvatarBase64String = (String) currentAccountPrefs.getData().getOrDefault("avatar_img", "nope");;
String accountPasswordUpdate = currentAccount.getPasswordUpdate();
String accountEmail = (String) currentAccount.getEmail();
String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
ProfileFragment.this.getContext().getApplicationContext(),
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSX", Locale.US);
try {
Date dateLastPasswordUpdate = sdf.parse(accountPasswordUpdate);
Date dateSessionCreate = sdf.parse(loggedSessionCreateData);
if (dateLastPasswordUpdate.after(dateSessionCreate)) {
account.deleteSession(
currentSessionString,
new Continuation<Object>() {
@NotNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resumeWith(@NotNull Object o) {
try {
if (o instanceof Result.Failure) {
Result.Failure failure = (Result.Failure) o;
throw failure.exception;
} else {
}
} catch (Throwable th) {
Log.e("ERROR", th.toString());
}
}
});
editor.clear();
editor.putString("savedStatus", "false");
editor.apply();
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(ProfileFragment.this.getContext().getApplicationContext(), getResources().getString(R.string.wrongCredentials), Toast.LENGTH_LONG);
toast.show();
}
});
}
System.out.println(accountPasswordUpdate);
} catch (ParseException e) {
e.printStackTrace();
}
if (!(loggedEmail.equals(accountEmail))) {
account.deleteSession(
currentSessionString,
new Continuation<Object>() {
@NotNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resumeWith(@NotNull Object o) {
try {
if (o instanceof Result.Failure) {
Result.Failure failure = (Result.Failure) o;
throw failure.exception;
} else {
editor.clear();
editor.putString("savedStatus", "false");
}
} catch (Throwable th) {
Log.e("ERROR", th.toString());
}
}
});
editor.clear();
editor.putString("savedStatus", "false");
editor.apply();
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(ProfileFragment.this.getContext().getApplicationContext(), getResources().getString(R.string.wrongCredentials), Toast.LENGTH_LONG);
toast.show();
}
});
}
editor.putString("savedUsername", currentUsername);
editor.putString("savedCreateData", currentCreateData);
editor.putString("savedMainInfo", currentMainInfoString);
if (currentAvatarBase64String != null) {
editor.putString("savedAvatar", currentAvatarBase64String);
}
editor.apply();
}
} catch (java.lang.RuntimeException unkException) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(ProfileFragment.this.getContext().getApplicationContext(), getResources().getString(R.string.wrongInternetConnection), Toast.LENGTH_LONG);
toast.show();
}
});
} catch (Throwable th) {
Log.e("ERROR", th.toString());
}
}
});
TextView loginWarningTextView = getView().findViewById(R.id.loginWarningTextView);
loginWarningTextView.setVisibility(View.GONE);
Button loginWarningButton = getView().findViewById(R.id.loginWarningButton);
loginWarningButton.setVisibility(View.GONE);
LinearLayout loginWarningButtonLayout = getView().findViewById(R.id.loginWarningButtonLayout);
loginWarningButtonLayout.setVisibility(View.GONE);
TextView profileInfoNameTextView = getView().findViewById(R.id.profileInfoNameTextView);
profileInfoNameTextView.setText(loggedUsername);
TextView profileInfoMainTextView = getView().findViewById(R.id.profileInfoMainTextView);
profileInfoMainTextView.setText(loggedMainInfo);
ImageView profileInfoAvatarImageView = getView().findViewById(R.id.profileInfoAvatarImageView);
if (loggedAvatarBase64String != null) {
decodedString = Base64.decode(loggedAvatarBase64String, Base64.DEFAULT);
decodedBitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
profileInfoAvatarImageView.setImageBitmap(decodedBitmap);
}
}
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (AppwriteException e) {
throw new RuntimeException(e);
}
Источник: Stack Overflow на русском