android - Cannot control Progressbar visibility from onActivityResult in Fragment
问题描述
I have a Fragment which contains a Progressbar. I retrieve it in onCreateView()
method where setVisibility()
works fine.
Now, when I try to set visibility of the same progressbar (declared in fragment at class level) inside onActivityResult()
nothing happens. Here is the code.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE_PROFILE_VIDEO_PATH){
if(resultCode == Activity.RESULT_OK) {
String profileVideoPath = data.getExtras().getString(ProfileVideoRecordingActivity.VIDEO_PROFILE_PATH);
Log.d("DEBUG", profileVideoPath);
//Upload to server
File profileVideo = new File(profileVideoPath);
if(profileVideo.exists()) {
pbarVideoUpload.setVisibility(View.VISIBLE);
FireBaseWrapper fileUploader = new FireBaseWrapper();
String serverFolderPath = "videoprofile";
String contentType = "video/mp4";
FireBaseAfterUpload afterUpload = new FireBaseAfterUpload() {
@Override
public void onSuccess(String uploadURL) {
Log.d("DEBUG", "Successfully uploaded video to server");
Log.d("DEBUG", uploadURL);
pbarVideoUpload.setVisibility(View.GONE);
ProfileService profileService = new ProfileService(TAG) {
@Override
protected void onPreServiceCall() {
}
@Override
protected void onPostServiceCall() {
}
@Override
public void afterSuccess(Object object) {
ReturnCode successCode = (ReturnCode) object;
if(successCode.getSuccess()){
Log.d("DEBUG", "Profile Video URL updated in DB");
}else{
Log.d("DEBUG", "Profile Video URL NOT updated in DB");
}
}
@Override
public void afterError() {
Log.d("DEBUG", "Profile Video URL NOT updated in DB");
}
};
profileService.updateVideoPath(uploadURL);
}
@Override
public void onProgress(String data) {
}
@Override
public void onFaliure() {
Log.d("DEBUG", "Error! Didn't upload");
pbarVideoUpload.setVisibility(View.GONE);
}
};
try {
fileUploader.upload(profileVideo, profileVideo.getName(), serverFolderPath, afterUpload, contentType, false);
}catch (FileNotFoundException e){
Log.e("DEBUG", "FileNotFoundException", e);
}
}
}
}
}
I tried calling setVisibility()
inside an Handler and also on UI thread using runOnUiThread()
. Both approaches didn't work.
How can I control visibility of progressbar inside onActivityResult()
of Fragment?
I need it as I am uploading a file inside onActivityResult()
and need to display progress.
解决方案
我认为你 onActivityResult 没有像在片段中那样触发。请在包含片段的活动中使用以下代码。
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag(fragmentTag);
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, intent);
}
}