how to return result from asyn call - java

i have all my async calls in their own classes and so i dont want to have global vars being set aync'ly. To do this i want to return objects eg a string from my asunc postProcess methods.
can this be done?
Below is my general structure to my classes, i want to return a String for example from onPostExecute(). I see delegates are mentioned in other places but this seems very messy, sure there is a way to have a return type to the class or methods?
class GetStuffAsyncly extends AsyncTask<String, String, String>
{
// my vars....
public myconstructor(String dialogMessage, Context con)
{
this.qDialog = new ProgressDialog(con);
this.dialogString = dialogMessage;
this.context = con;
}
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
do stuff like fire dialog
}
#Override
protected String doInBackground(String... args)
{
// do stuff in background...
return data;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String jsonString)
{
// dismiss the dialog after getting all data
dialog.dismiss();
}
}

Some thing like below
class GetStuffAsyncly extends AsyncTask<String, String, String> {
String dialogString;
ProgressDialog dialog;
Context context;
AsyncListener listener;
// my vars....
public GetStuffAsyncly(String dialogMessage, Context con, AsyncListener listener) {
this.dialog = new ProgressDialog(con);
this.dialogString = dialogMessage;
this.context = con;
this.listener = listener;
}
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
listener.onTaskStarted();
}
#Override
protected String doInBackground(String... args) {
// do stuff in background...
return data;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String jsonString) {
// dismiss the dialog after getting all data
dialog.dismiss();
listener.onTaskFinished(jsonString);
}
}
And the listener class
public interface AsyncListener {
void onTaskStarted();
void onTaskFinished(String data);
}
and you can call like this
new GetStuffAsyncly(message, this, new AsyncListener() {
#Override
public void onTaskStarted() {
//do your stuff
}
#Override
public void onTaskFinished(String data) {
//Do your stuff;
}
}).execute(parameter);

Another option is to use AsyncTaskLoader. You derive your class not from AsyncTask, but from AsyncTaskLoader. In your Activity you need to implement LoaderCallbacks interface. The args you want to use in Loader, you put in Bundle. All information you want to get from Loader will be passed in method onLoadFinished(). Here's an example
public class BaseInitLoader extends AsyncTaskLoader<Employee[]> {
Context mContext;
boolean firstrun;
public BaseInitLoader(Context context, Bundle args) {
super(context);
mContext = context;
firstrun = args.getBoolean("firstrun");
}
#Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad();
}
#Override
public Employee[] loadInBackground() {
MainActivity activity =(MainActivity) mContext;
Cursor cursor = new DatabaseFiller(activity.getDb(), mContext, firstrun).fillTable();
ArrayList<Employee> list = new ArrayList<>();
QueryResultIterable<Employee> itr = null;
try {
itr = cupboard().withCursor(cursor).iterate(Employee.class);
for(Employee employee: itr){
list.add(employee);
}
} finally {
// close the cursor
if (itr != null) {
itr.close();
}
}
Employee[] employees = new Employee[list.size()];
employees = list.toArray(employees);
return employees;
}
}
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks, View.OnClickListener {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
TextView priority, name, innerPhone, mobilePhone, position;
Button cityBtn;
CharSequence[] cities;
SQLiteDatabase db;
Context mContext;
private Cursor cursor;
private SQLiteDatabase database;
private ListView listView;
private TextView nameTxt;
private EmployeeAdapter adapter;
public static final String LOG_TAG = "Database";
SharedPreferences prefs;
private boolean firstrun;
private ViewPager viewPager;
private TabLayout tabLayout;
private final int INITIAL = 1;
private final int SORT_NAME = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
Bundle args = new Bundle();
prefs = getSharedPreferences("ua.lanet.PipBoy", MODE_PRIVATE);
if(prefs.getBoolean("firstrun", true)){
args.putBoolean("firstrun", true);
prefs.edit().putBoolean("firstrun", false).apply();
}
else{
args.putBoolean("firstrun", false);
}
getLoaderManager().initLoader(INITIAL, args, this);
PipBoyDataHelper helper = new PipBoyDataHelper(this);
db = helper.getWritableDatabase();
}
public SQLiteDatabase getDb() {
return db;
}
#Override
public Loader onCreateLoader(int id, Bundle args) {
return new BaseInitLoader(mContext, args);
}
#Override
public void onLoadFinished(Loader loader, Object data) {
//do something with the data. Cast Object to your return type of loader
}
#Override
public void onLoaderReset(Loader loader) {
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.text:
getLoaderManager().initLoader(SORT_NAME, null, this);
break;
}
}
private class ViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
}

Related

Android how to Check if language has changed

I create an application with MVVM concept, there is fragment for viewpager in my Activity. some data changed when I change my language in my application, but the data that showed by webservices is not change. so I try to add android:configChanges="locale" in my every Activity and I already add this code on my Activity class :
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
recreate();
}
}
But its make my UI recreate every configuration change, including Screen Rotation while I just want to recreate if Language is changed.
this is my fragment code :
public class CatalogueFragment extends BaseFragment<FragmentCatalogueBinding, CatalogueViewModel>
implements CatalogueNavigator, CatalogueAdapter.CatalogueAdapterListener {
#Inject
CatalogueAdapter adapter;
#Inject
LinearLayoutManager mLayoutManager;
#Inject
ViewModelProvider.Factory factory;
FragmentCatalogueBinding fragmentCatalogueBinding;
private CatalogueViewModel catalogueViewModel;
public static CatalogueFragment newInstance(int Pos) {
Bundle args = new Bundle();
CatalogueFragment fragment = new CatalogueFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public int getBindingVariable() {
return BR.viewModel;
}
#Override
public int getLayoutId() {
return R.layout.fragment_catalogue;
}
#Override
public CatalogueViewModel getViewModel() {
catalogueViewModel = ViewModelProviders.of(this, factory).get(CatalogueViewModel.class);
return catalogueViewModel;
}
#Override
public void handleError(String error) {
// handle error
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
catalogueViewModel.setNavigator(this);
adapter.setListener(this);
}
#Override
public void onRetryClick() {
catalogueViewModel.fetchData();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fragmentCatalogueBinding = getViewDataBinding();
setUp();
}
#Override
public void updateData(List<Movie> movieList) {
adapter.addItems(movieList);
}
private void setUp() {
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
fragmentCatalogueBinding.recyclerCatalogue.setLayoutManager(mLayoutManager);
fragmentCatalogueBinding.recyclerCatalogue.setItemAnimator(new DefaultItemAnimator());
fragmentCatalogueBinding.recyclerCatalogue.setAdapter(adapter);
}
}
and this is my ViewModel class
public class CatalogueViewModel extends BaseViewModel {
private final MutableLiveData<List<Movie>> movieListLiveData;
public CatalogueViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) {
super(dataManager, schedulerProvider);
movieListLiveData = new MutableLiveData<>();
fetchData();
}
public void fetchData() {
setIsLoading(true);
getCompositeDisposable().add(getDataManager()
.getApiHelper().doMovieCall(URLConfig.API_KEY, getDataManager().getLanguage())
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(movieResponse -> {
if (movieResponse != null && movieResponse.getResults() != null) {
movieListLiveData.setValue(movieResponse.getResults());
}
setIsLoading(false);
}, throwable -> {
setIsLoading(false);
// getNavigator().handleError(throwable);
}));
}
public LiveData<List<Movie>> getMovieListLiveData() {
return movieListLiveData;
}
}
Can anybody show me where is my wrong? Thank you very much
You can use: ACTION_LOCALE_CHANGED
Here an example:
private BroadcastReceiver mLangReceiver = null;
protected BroadcastReceiver setupLangReceiver(){
if(mLangReceiver == null) {
mLangReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do what you want
}
};
registerReceiver(mLangReceiver, new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
}
return mLangReceiver;
}

Why ReferenceQueue always empty in activity?

I'm trying using ReferenceQueue to check Activity if the activity is destory,Whether this activity is recycled.
I just using intent to Main2Activity.class:
switch (v.getId()){
case R.id.btn_turn_two:
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
break;
default:
break;
}
when I press to return MainActivity.class, the Main2Acitivity.class will be destroyed, so I using registerActivityLifecycleCallbacks watch activity in application,
public class MainApplication extends Application{
private watche watche;
#Override
public void onCreate() {
super.onCreate();
watche=new watche(this,getApplicationContext());
}
this class is check the Activity is destoryed.
public class watche {
KeyRefrence ref;
private Context context;
private final Set<String> retainedKeys = new CopyOnWriteArraySet<>();
private final ReferenceQueue<Object> referenceQueue=new ReferenceQueue<>();
public watche(Application application, Context context){
application.registerActivityLifecycleCallbacks(lifecycleCallbacks);
this.context=context;
}
Application.ActivityLifecycleCallbacks lifecycleCallbacks=new Application.ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
//weakrefrence to this activity
String key = UUID.randomUUID().toString();
retainedKeys.add(key);
final KeyRefrence weakReference=new KeyRefrence(activity,key,activity.getPackageName(),referenceQueue);
final MyAyTask myAyTask=new MyAyTask(weakReference,activity,context);
myAyTask.doInBackground(null);
}
};
public class MyAyTask extends AsyncTask {
private Activity activity;
private KeyRefrence keyRefrence;
private Context context;
public MyAyTask(KeyRefrence keyRefrence, Activity activity,Context context){
this.activity=activity;
this.context=context;
this.keyRefrence=keyRefrence;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
#Override
protected Object doInBackground(Object[] objects) {
gc();
ref=(KeyRefrence)referenceQueue.poll();
if (ref==null){
Log.d(TAG, "onActivityDestroyed:Acitivty is not destory");
}
else if (ref!=null){
Log.d(TAG, "doInBackground: "+ref);
}
return null;
}
}
I have create KeyReference implement WeakReference,and I didn't do anything in Main2Activity.class, I just press the phone return,I check the gc,is working ,but the referencequeue always empty, I'm sure the Activity is destoryed.

Android custom Progress Dialog - setCancelable()

I had created a custom Progress Dialogue. Overriding properties like setCancelable() , setCanceledOnTouchOutside() doesn't worked for me.
public class CustomProgressDialogue extends ProgressDialog {
private final Context context;
public CustomProgressDialogue(Context context) {
super(context);
this.context = context;
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_view);
}
// Didn't worked
#Override
public void setCancelable(boolean flag) {
super.setCancelable(false);
}
// Didn't worked
#Override
public void setCanceledOnTouchOutside(boolean cancel) {
super.setCanceledOnTouchOutside(false);
}
}
But the same time applying same properties after the instance creation worked.
// Worked
progressDialogue = new CustomProgressDialogue(getContext());
progressDialogue.setCancelable(false);
progressDialogue.setCanceledOnTouchOutside(false);
Could you please somebody can explain this?
instead of overriding the cancel-able method create a static method like this and then pass it the required options
here's how ProgressDialog class do this:
public static ProgressDialog show(Context context, CharSequence title,
CharSequence message, boolean indeterminate,
boolean cancelable, OnCancelListener cancelListener) {
ProgressDialog dialog = new ProgressDialog(context);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setIndeterminate(indeterminate);
dialog.setCancelable(cancelable);
dialog.setOnCancelListener(cancelListener);
dialog.show();
return dialog;
}
You can try with this way
public class CustomProgressDialogue extends ProgressDialog
{
public static ProgressDialog(Context context) { // This section create Main role .
CustomProgressDialogue dialog = new CustomProgressDialogue (context);
dialog.setCancelable(false); // Add this
return dialog;
}
public CustomProgressDialogue (Context context) {
super(context);
}
public CustomProgressDialogue (Context context, int theme) {
super(context, theme);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_view);
}
#Override
public void show() {
super.show();
}
#Override
public void dismiss()
{
super.dismiss();
}
}
you cann add
public static ProgressDialog(Context context) {
CustomProgressDialogue dialog = new CustomProgressDialogue (context);
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
my method is
final AlertDialog alertD = new AlertDialog.Builder(context).create();
alertD.setCanceledOnTouchOutside(false);
is work...!
The issue with your code is that you are overriding the cancelable and OutsideTouchCancel in your CustomDialog class but you are not replacing the original code from ProgressDialog class. So when you call super(context) on your constructor it will initiate your dialog with its build in function for Cancelable and OutsideTouchCancel.
So in your constructor of CustomDialog you need to explicitly call
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false)
You are not required to override those function in your custom class.

How to initialize interface instance to communicate with child fragment inside parent fragment

Good day, I have a fragment called MainFragment called from MainActivity. Inside MainFragment I have private OnProgressUpdateListener progressListener; this interface instance helps me talk to ProgressDialog Fragment.
I'm able to initialize interface instance inside my activities but I'm getting ClassCastException when I attempt to initialize the interface instance inside MainFragment
Below are my classes:
--------------------------------------------------------------------------------
Interface
--------------------------------------------------------------------------------
public interface OnProgressUpdateListener
{
void onProgressUpdate(String message);
void onDismissDialog();
}
--------------------------------------------------------------------------------
Child Fragment to MainFragment
--------------------------------------------------------------------------------
public class ProgressbarDialog extends DialogFragment implements OnProgressUpdateListener
{
TextView progressMessage;
ProgressBar progressBar;
View dialogView;
LayoutInflater inflater;
AlertDialog alertDialog;
AlertDialog.Builder dialogBuilder;
public ProgressbarDialog()
{
}
public static ProgressbarDialog newInstance(String title, String message)
{
ProgressbarDialog fragment = new ProgressbarDialog();
Bundle args = new Bundle();
args.putCharSequence("title", title);
args.putCharSequence("message", message);
fragment.setArguments(args);
return fragment;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
dialogBuilder = new AlertDialog.Builder(getActivity());
inflater = getActivity().getLayoutInflater();
dialogView = inflater.inflate(R.layout.content_progressdialog,null);
dialogBuilder.setView(dialogView);
progressBar = dialogView.findViewById(R.id.pbProgressSpinner);
progressMessage = dialogView.findViewById(R.id.tvProgressMessage);
dialogBuilder.setTitle(getArguments().getString("title"));
progressBar.setIndeterminate(true);
progressMessage.setText(getArguments().getString("message"));
alertDialog = dialogBuilder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
return alertDialog;
}
#Override
public void onProgressUpdate(String message)
{
progressMessage.setText(message);
}
#Override
public void onDismissDialog()
{
alertDialog.dismiss();
}
}
--------------------------------------------------------------------------------
MainFragment - Parent Fragment To ProgressbarDialog
--------------------------------------------------------------------------------
public class MainFragment extends Fragment
{
private View mainView;
private CheckBox rememberMe;
private boolean stayLoggedIn;
private CountDownLatch latch;
private FragmentManager manager;
private OnMainListener mListener;
private EditText email, password;
private ProgressbarDialog progressDialog;
private OnProgressUpdateListener progressListener;
private final int REGISTER_CODE = 1, RESET_CODE = 2;
private FloatingActionButton fabRegister, fabLogin, fabReset;
public MainFragment()
{}
public static MainFragment newInstance()
{
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getArguments() != null)
{}
manager = getChildFragmentManager();
progressDialog = ProgressbarDialog.newInstance("Authentication", "Connecting To Server, Please Wait...");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
mainView = inflater.inflate(R.layout.main_fragment, container, false);
stayLoggedIn = false;
rememberMe = mainView.findViewById(R.id.cbRememberMe);
email = mainView.findViewById(R.id.edtLoginEmail);
password = mainView.findViewById(R.id.edtLoginPassword);
fabRegister = mainView.findViewById(R.id.fabRegister);
fabLogin = mainView.findViewById(R.id.fabLogin);
fabReset = mainView.findViewById(R.id.fabReset);
return mainView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
email.setTag("Account Email Required!");
password.setTag("Account Password Required!");
}
#Override
public void onStart()
{
super.onStart();
rememberMe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
stayLoggedIn = b;
}
});
fabRegister.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
mListener.onFABInteraction(REGISTER_CODE);
}
});
fabLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
onLoginRequest();
}
});
fabReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
mListener.onFABInteraction(RESET_CODE);
}
});
}
#Override
public void onAttach(Context context)
{
super.onAttach(context);
try
{
if (context instanceof OnMainListener)
{
mListener = (OnMainListener) context;
}
else
{
throw new RuntimeException(context.toString()
+ " must implement OnMainListener");
}
}
catch (Exception e)
{
Log.e(MainFragment.class.getName(), e.getMessage());
}
}
**#Override
public void onAttachFragment(Fragment childFragment) {
super.onAttachFragment(childFragment);
if(childFragment instanceof OnProgressUpdateListener)
{
progressListener = (OnProgressUpdateListener) childFragment;
//This code is never executed
}
}**
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
interface OnMainListener
{
void onLoginSuccess(BackendlessUser user);
void onFABInteraction(int option);
}
private class OnAuthentication extends AsyncTask<String, String, BackendlessUser>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
latch = new CountDownLatch(1);
progressDialog.show(manager, MainFragment.class.getName());
Code Fails here, null pointer exception is thrown because progressListener interface instance is not initialised.
progressListener.onProgressUpdate("Authenticating User, Please Wait...");
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
progressListener.onProgressUpdate(values[0]);
}
#Override
protected BackendlessUser doInBackground(String... strings)
{
try
{
Backendless.UserService.login(
Utility.getText(email),
Utility.getText(password),
onLoginCallback, stayLoggedIn);
publishProgress("Validating Credentials, Please Wait...");
latch.await();
}
catch (InterruptedException e)
{
publishProgress(e.getMessage());
}
return Utility.loginUser;
}
#Override
protected void onPostExecute(BackendlessUser user)
{
super.onPostExecute(user);
Utility.clearViews(email, password, rememberMe);
progressListener.onDismissDialog();
if(user != null)
{
if(((MainActivity)getActivity()).onRoleValidation(user))
{
mListener.onLoginSuccess(user);
}
else
{
//send a push notification to master channel
Utility.sendNotification(getActivity(),
"New Application User",
"New Registration",
"New User Awaiting Role Assignment", "Master",
"Role Assignment Pending For User :"
+ user.getEmail()
+ ":" + user.getProperty("name").toString()
+ " " + user.getProperty("surname").toString());
}
}
}
}
private void onLoginRequest()
{
if(Utility.hasText(email, password))
{
if(Utility.isEmailValid(Utility.getText(email)))
{
new OnAuthentication().
execute(Utility.getText(email),
Utility.getText(password));
}
else
{
Utility.showToast(getActivity(), "Invalid Email");
Utility.clearViews(email);
}
}
}
private AsyncCallback<BackendlessUser> onLoginCallback = new AsyncCallback<BackendlessUser>()
{
#Override
public void handleResponse(BackendlessUser backendlessUser)
{
latch.countDown();
Utility.loginUser = backendlessUser;
Log.i(MainFragment.class.getName(), "Login Successful!\n" + backendlessUser.getUserId());
}
#Override
public void handleFault(BackendlessFault backendlessFault)
{
latch.countDown();
progressListener.onProgressUpdate("Login Unsuccessful!");
Log.e(MainFragment.class.getName(), "Login Failed!\n" + backendlessFault.getMessage());
}
};
}

java.lang.IllegalStateException: Fragment not attached to Activity issue in android

I am facing strange issue during call of my activity with Fragment usage. I am getting error like,
java.lang.IllegalStateException: Fragment ScoreFragment{ee2b833
id=0x7f0e0198} not attached to Activity
On line 146. My Fragment code which have error is line like below
if(mPageFlag.equalsIgnoreCase(getString(R.string.winners))){
And My full code for same is below,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPageFlag = getArguments().getString(ARG_PAGE_FLAG);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser && !mIsPageLoaded){
mContext = getActivity();
mIsPageLoaded = true;
if(mPageFlag.equalsIgnoreCase(getString(R.string.winners))){
new getcontestscorewinners(mContext).execute();
}else{ //
new getcontestscorewinnersNew(mContext).execute();
}
}
}
public class getcontestscorewinners extends AsyncTask<String, Void, String> {
boolean response = false;
private Context mContext;
public getcontestscorewinners(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(mContext, "Processing...",
"Please wait....");
}
#Override
protected String doInBackground(String... params) {
NetworkTask.getContestScoreWinners(winnerHandler);
return "";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Let me know if someone can help me for get out of it. Thanks.
Try using isAdded():
Return true if the fragment is currently added to its activity.
So your code should be like this :
if(isAdded() && mPageFlag.equalsIgnoreCase(getString(R.string.winners))){

Categories