Anthony Rodriguez
Anthony Rodriguez

Reputation: 3

AsynkTask within Fragment within a ViewPager

First of all, I am relatively new to android programming.

I am creating a ViewPager application with two Fragments. One of the Fragments requests data from a server and return a result to the main FragmentActivity. My problem is that this request to the server can take sometime, and I have been trying to get a ProgressDialog to appear with AsyncTask while the user waits for the data to be retrieved. Once I create the background thread to retrieve the data, I successfully execute some code in the onPostExecute() method and set some variables. However, the return statement that sends information back to the FragmentActivity is being executed before the background thread actually ends. I can't seem to figure out a way for the main thread to wait on the background thread. Using Asyctask's get() method results in the ProgressDialog from appearing. I have looked through a lot of posts in here, but can't seem to find an answer.

Anything helps.

Code below:

SplashScreen.java

public class SplashScreen extends FragmentActivity {
    MainMenu mainMenu;
    MapScreen mapScreen;
    PagerAdapter pagerAdapter;
    ViewPager viewPager;
    List<LatLng> geoPoints;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

            setContentView(R.layout.activity_splash_screen);
            context = this;

            initializePaging();
    }

    private void initializePaging()
    {
            mainMenu = new MainMenu();
            mapScreen = new MapScreen();

            pagerAdapter = new PagerAdapter(getSupportFragmentManager());
            pagerAdapter.addFragment(mainMenu);
            pagerAdapter.addFragment(mapScreen);

            viewPager = (ViewPager) super.findViewById(R.id.viewPager);
            viewPager.setAdapter(pagerAdapter);
            viewPager.setOffscreenPageLimit(2);
            viewPager.setCurrentItem(0);

            viewPager.setOnPageChangeListener(new OnPageChangeListener()
            {
                    @Override
                    public void onPageScrollStateChanged(int postion){}
                    @Override
                    public void onPageScrolled(int arg0, float arg1, int arg2){}
                    @Override
                    public void onPageSelected(int position)
                    {
                    switch(position){
                            case 0: findViewById(R.id.first_tab).setVisibility(View.VISIBLE);
                                    findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
                                    break;

                            case 1:        findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
                                    findViewById(R.id.second_tab).setVisibility(View.VISIBLE);
                                    break;
                            }
                    }
            });
}

    //Called from onClick in main_mainu.xml
    public void getDirections(View view)
    {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

            try
            {
                    geoPoints = mainMenu.getDirections(context);
                    mapScreen.plotPoints(geoPoints);

            }
            catch(Exception e)
            {
                    Toast.makeText(getApplicationContext(), "Error! Invalid address entered.", Toast.LENGTH_LONG).show();
                    mainMenu.clear();
            }

    }

}

MainMenu.java

public class MainMenu extends Fragment {

    String testString;
    int testInt;
    TextView testTV;
    private TextView tvDisplay;
    private EditText departure;
    private EditText destination;
    private Geocoder geocoder;
    private List<Address> departAddress;
    private List<Address> destinationAddress;
    private List<LatLng> geoPoints;
    private String departString;
    private String destinationString;
    private Address departLocation;
    private Address destinationLocation;
    private LatLng departurePoint;
    private LatLng destinationPoint;
    private Context contextMain;
    private GetData task;

    public MainMenu()
    {
            super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
            View root = (View) inflater.inflate(R.layout.main_menu, null);

            geoPoints = new ArrayList<LatLng>(2);

            return root;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
            departure = (EditText) getView().findViewById(R.id.depart_field);
            destination = (EditText) getView().findViewById(R.id.destination_field);

            tvDisplay = (TextView) getView().findViewById(R.id.textView1);

    }

    public List<LatLng> getDirections(Context context)
    {       
            contextMain = context;
            geocoder = new Geocoder(getActivity());

            departString = departure.getText().toString();
            destinationString = destination.getText().toString();

            try
            {
                    task = new GetData(new Callback(){
                            public void run(Object result)
                            {
                                    //return geoPoints;
                            }
                    });
                    task.execute((Void[])null);
            }catch(Exception e)
            {
                    e.printStackTrace();
            }

            return geoPoints; 
    }

    public void clear()
    {
            departure.setText("");
            destination.setText("");
            tvDisplay.setText("Enter departure point, and destination point");
    }

    private class GetData extends AsyncTask<Void, Void, List<List<Address>>>
    {
            Callback callback;
            private ProgressDialog processing;

            public GetData(Callback callback)
            {
                    this.callback = callback;
            }

            @Override
            protected void onPreExecute()
            {
                    processing = new ProgressDialog(contextMain);
                    processing.setTitle("Processing...");
                    processing.setMessage("Please wait.");
                    processing.setCancelable(false);
                    processing.setIndeterminate(true);
                    processing.show();

            }

            @Override
            protected List<List<Address>> doInBackground(Void...arg0)
            {       
                    List<List<Address>> list = new ArrayList<List<Address>>(2);

                    try
                    {
                            departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
                            destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);

                            list.add(departAddress);
                            list.add(destinationAddress);

                    }catch(IOException e)
                    {
                            e.printStackTrace();
                    }

                    return list;
            }

            @Override
            protected void onPostExecute(List<List<Address>> list)
            {
                    departLocation = list.get(0).get(0);
                    destinationLocation = list.get(1).get(0);

                    departurePoint = new LatLng(departLocation.getLatitude(), departLocation.getLongitude());
                    destinationPoint = new LatLng(destinationLocation.getLatitude(), destinationLocation.getLongitude());

                    if(geoPoints.size() >= 2)
                    {
                            geoPoints.clear();
                    }

                    geoPoints.add(departurePoint);
                    geoPoints.add(destinationPoint);

                    callback.run(list);
                    processing.dismiss();
            }
    }

}

Upvotes: 0

Views: 261

Answers (1)

Android Noob
Android Noob

Reputation: 3341

        @Override
        protected Object doInBackground(Void...arg0)
        {
                Object result = null;

                try
                {
                        departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
                        destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);

                }catch(IOException e)
                {
                        e.printStackTrace();
                }

                return result;
}

You never set the value of result...

Upvotes: 1

Related Questions