I have a working AsyncTask to get data from a server and display it in a TextView. But is it possible to output the data into a TextView which is located in a fragment? So let's say, the AsyncTask is loaded in the MainActivity and the output will be in a fragment.
This is my AsyncTask:
private static class FtpDownload extends AsyncTask<String, String, String> {
private WeakReference<GuidanceActivity> activityWeakReference;
FtpDownload(GuidanceActivity activity) {
activityWeakReference = new WeakReference<>(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... FTPconnection) {
GuidanceActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return null;
}
try {
FTPClient ftpClient = new FTPClient();
ftpClient.connect("", 21);
System.out.println(ftpClient.getReplyString());
ftpClient.enterLocalPassiveMode();
ftpClient.login("anonymous", "");
ftpClient.changeWorkingDirectory("/");
InputStream inStream = ftpClient.retrieveFileStream(".html");
activity.contents = IOUtils.toString(inStream, StandardCharsets.UTF_8);
System.out.println(activity.contents);
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String output) {
GuidanceActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
TextView textView = activity.findViewById(R.id.text_view);
textView.setText(Html.fromHtml(activity.contents));
}
}
In your fragment:
public class MyFragment extends Fragment {
TextView myTextView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = View root = inflater.inflate(R.layout.my_frag_layout, null);
myTextView = (TextView) view.findViewById(R.id.myTextView);
//rest of your implementation of onCreateView
return view;
}
//this will be called from activity
public void updateTextView(String text) {
myTextView.setText(text);
}
}
in your activity:
public class MyActivity extends AppCompatActivity {
private final String FRAGMENT_TAG = "myFragment";
private static class FtpDownload extends AsyncTask<String, String, String> {
//rest of your FtpDownload class
#Override
protected void onPostExecute(String output) {
GuidanceActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG );
/* or
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment );
if your fragment is in an xml layout */
fragment.updateTextView(Html.fromHtml(activity.contents));
}
}
}
Yes, it is possible. This is a sample for WiFi scanning from MainActivity and the results are show at fragment. I believe you can understand the logic and convert it for your project
MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentDiscoverWiFi.ScanWiFi;
//public variable
FragmentDiscoverWiFi fragmentDiscoverWiFi;
//This will be called from your fragment
#Override
public void onScanWiFi(FragmentDiscoverWiFi fragment) {
fragmentDiscoverWiFi = fragment;
}
//use something like this when your want to update fragment
fragmentDiscoverWiFi.onScanWiFiComplete();
Fragment:
public class FragmentDiscoverWiFi extends Fragment {
private Context mContext;
public interface ScanWiFi {
public void onScanWiFi(FragmentDiscoverWiFi fragment);
}
public FragmentDiscoverWiFi() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
mContext = context;
super.onAttach(context);
}
public void onScanWiFiComplete() {
if (!isDetached()) {
//Access your data from MainActivity like this:
Log.d(TAG, "Total APs:" + ((MainActivity) mContext).wifiScanResults.size());
}
}
#Override
public void onResume() {
super.onResume();
if (!getUserVisibleHint()) {
return;
}
pullToRefreshText = rootView.findViewById(R.id.pullToRefreshText);
pullToRefresh = rootView.findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.d(TAG, "refreshing...");
pullToRefresh.setRefreshing(true);
((MainActivity)mContext).onScanWiFi(FragmentDiscoverWiFi.this);
}
});
}
}
Related
Bellow there is some of the code of my application. The part where I need help is in requireActivity() in SettingFragment.java:
MainActivity.java
...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
}
public void iniciarIntent3() { //this method is called by a button in activity_main.xml
Intent intent = new Intent(this, Settings.class);
startActivityForResult(intent, 1);
}
}
Settings.java
...
public class Settings extends AppCompatActivity implements SettingsFragment.SendToActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
}
}
#Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof SettingsFragment) {
SettingsFragment settingsFragment = (SettingsFragment) fragment;
settingsFragment.setSendToActivity(this);
}
}
public void send(int result) {
...
}
}
SettingsFragment.java
public class SettingsFragment extends PreferenceFragmentCompat {
SendToActivity callback;
public void setSendToActivity (SendToActivity callback) {
this.callback = callback;
}
public interface SendToActivity {
void send(int result);
}
if (editTextPreference != null) {
editTextPreference.setOnBindEditTextListener(new
EditTextPreference.OnBindEditTextListener() {
#Override
public void onBindEditText(#NonNull EditText editText) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setText("");
editText.setBackground(ContextCompat.getDrawable(requireActivity()
.getApplicationContext(), R.drawable.fondo_edittextpreference));
}
});
}
...
}
I just want to be sure that requireActivity() in SettingsFragment class is not going to throw a nullpointerexeption. Can you help me to check?
Instead of requireActivity().getApplicationContext() you could do either of the following
editText.setBackground(ContextCompat.getDrawable(editText.getContext(), R.drawable.fondo_edittextpreference))
editText.setBackgroundResource(R.drawable.fondo_edittextpreference)
requireActivity()
can throw null if the Activity is null for whatever reason that may be.
I believe that can be null if the user exists the application or forefully stops it etc. Or there was never one created in the context that youre in
Just do a try-catch
Activity activity;
try {
activity = requireActivity()
editText.setBackground(
ContextCompat.getDrawable(
activity.getApplicationContext(),
R.drawable.fondo_edittextpreference));
} catch (NullPointerException orTypeOfException) {
//handle here when the activity is null
}
I created my test project where i code to communicate between two fragments but actully I want to access activity from fragment.
Here is code to connect fragment to fragment, its working absolutely right without any error but now i want to change this code to connect activity from fragment instead of fragment to fragment communication.
So Please change this code to access activities from fragment. I stuck on this issue for than a week.So Guys please resolve this.
here is my mainaactivity:
public class MainActivity extends AppCompatActivity implements FragmentA.FragmentAListener, FragmentB.FragmentBListener {
private FragmentA fragmentA;
private FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA = new FragmentA();
fragmentB = new FragmentB();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_a, fragmentA)
.replace(R.id.container_b, fragmentB)
.commit();
}
#Override
public void onInputASent(CharSequence input) {
fragmentB.updateEditText(input);
}
#Override
public void onInputBSent(CharSequence input) {
fragmentA.updateEditText(input);
}
Here is my FragmentA.java:
public class FragmentA extends Fragment {
private FragmentAListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentAListener {
void onInputASent(CharSequence input);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_a, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInputASent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentAListener) {
listener = (FragmentAListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentAListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Here is my FragmentB.java:
public class FragmentB extends Fragment {
private FragmentBListener listener;
private EditText editText;
private Button buttonOk;
public interface FragmentBListener {
void onInputBSent(CharSequence input);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_b, container, false);
editText = v.findViewById(R.id.edit_text);
buttonOk = v.findViewById(R.id.button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence input = editText.getText();
listener.onInputBSent(input);
}
});
return v;
}
public void updateEditText(CharSequence newText) {
editText.setText(newText);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentBListener) {
listener = (FragmentBListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentBListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Here is my Fertilizers.java file which i want to access from FragmentA.:
public class Fertilizers extends AppCompatActivity {
RecyclerView mRecyclerView;
List<FertilizerData> myFertilizersList;
FertilizerData mFertilizersData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fertilizers);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
GridLayoutManager gridLayoutManager;
gridLayoutManager = new GridLayoutManager(Fertilizers.this, 1);
mRecyclerView.setLayoutManager(gridLayoutManager);
myFertilizersList = new ArrayList<>();
mFertilizersData = new FertilizerData("Urea Fertilizer","Urea is a concent","Rs.1900",R.drawable.urea);
myFertilizersList.add(mFertilizersData);
myFertilizersList.add(mFertilizersData); }
}
please write here a block of code to call Fertilzers Activity from FragmentA, I,ll be very thankful to you.
Calling getActivity() in your fragment gives you the calling activity so if MainActivity started your fragment then you would do
(MainActivity(getActivity())).something_from_your_main_activity
Solution found by itself regarding this issue.
FragmentHome.java class should look like this:
public class FragmentHome extends Fragment {
private Button button;
public FragmentHome(){
}
public interface OnMessageReadListener
{
public void onMessageRead(String message);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
button = (Button)v.findViewById(R.id.bn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Fertilizers.class);
intent.putExtra("some"," some data");
startActivity(intent);
}
});
return v;
}
}
FertilizersActivity.java should look like this:
public class Fertilizers extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fertilizers);
Bundle bundle = getIntent().getExtras();
if (bundle != null){
if(bundle.getStringArrayList("some") !=null){
Toast.makeText(getApplicationContext(),"data:" + bundle.getStringArrayList("some"),Toast.LENGTH_LONG).show();
}
}
}
}
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;
}
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());
}
};
}
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))){