0

This is the class I need to call a fragment's method on:

public class GetCurrentLocation extends AsyncTask<String, Void, String>{

private Context mContext;
private PostSolicitationFragment mPostSolicitationFragment = new PostSolicitationFragment();
private View view;

public GetCurrentLocation (View view, Context mContext) {
    this.view = view;
    this.mContext = mContext;
}


protected void onPreExecute() {
    super.onPreExecute();

}

protected String doInBackground(String... params) {
    //Code removed to shorten codeblock, it calls gps location here
    return null;
}

protected void onPostExecute(String result) {
    super.onPostExecute(result);
    mPostSolicitationFragment.setLocalText(); //This is the method it transfer the GPS address to the view
}
}

A Common answer is the following, but bear in mind that it does not work for me since I'm not calling it from another fragment or even activity, I'm calling it from a custom class.

NameofTheFragment fragment = getFragmentManager().findFragmentById(R.id.fragment);

I tried initializing the Fragment like so:

private PostSolicitationFragment mPostSolicitationFragment = new PostSolicitationFragment();

Problem with that is that I get a null object reference. Since I'm trying to edit an EditText inside the fragment's layout.

An alternative would be to make the call to the MainActivity, but I fall on the same old problem.

It would be awesome to simply do a ((MainActivity)getActivity()), but that doesn't work since I'm calling it from my AsyncTask class file.

How can I proceed?

Edit

Just so it makes a bit more sense, this is the setLocalText method inside the fragment:

public void setLocalText() {
    if (mLocalText != null) {
        mLocalText.setText(mMainVariables.getAddress());
    } else {
        Log.e("LOCALTEXT:", "NULLLLLLLLLLLLLLLL");
    }
}

mLocalText is initialized when the view is created (onCreateView) - PostSolicitationFragment:

    View view = inflater.inflate(R.layout.fragment_post_solicitation,
            container, false);

    mLocalText = (EditText) view.findViewById(R.id.localText);
Rosenberg
  • 2,424
  • 5
  • 33
  • 56
  • 1
    If the fragment initiates the async task, pass in a callback. If not, broadcast a message in `onPostExecute` and receive it in the fragment. – nasch May 06 '17 at 00:02
  • Problem is, I need to show GPS address *as soon* as the AsyncTask ends. I have no idea how to deal with a callback on this situation though. – Rosenberg May 06 '17 at 00:04
  • 1
    Pass the callback in to the AsyncTask constructor, and call it in `onPostExecute`. – nasch May 06 '17 at 00:08
  • Yes!! Callback worked. Thanks nasch! – Rosenberg May 06 '17 at 00:23

0 Answers0