1

This app searches for places of interest around you when you click a button. The flow is like this:

  • you click on the button Search
  • it checks for internet connection, if not, you get a dialog asking you to enable internet
  • you click on the button Search
  • it checks for location services, if not, you get a dialog asking you to enable location tracking and takes you to the Gps settings screen
  • then you go back, click on the button Search and an asynctask starts doing the job (searching and displaying)

What I need to do is eliminate the button Search, so it does everything automatically step by step. So it would be like:

  • start the app
  • it checks for internet connection, if not, you get a dialog asking you to enable internet
  • when internet enabled, it checks for location services, if not, you get a dialog asking you to enable location tracking and takes you to the Gps settings screen
  • then it starts the asynctask

I though that an alert dialog would make the activity paused and I could check all the conditions, but it looks like it doesn't. How should I solve this? Feel free to ask for any more details.

Forgot to mention that I only want this done once, the first time the app is started.

Here's my code:

public class MainActivity extends Activity {
    //variables

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv = (ListView) findViewById(R.id.list);
        button = (Button) findViewById(R.id.btn_show_map);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                cd = new ConnectionDetector(MainActivity.this);

                // Check if Internet present
                isInternetPresent = cd.isConnectingToInternet();
                if (!isInternetPresent) {
                    // Internet Connection is not present
                    alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please connect to a working Internet connection", false);
                    return;
                }

                // creating GPS Class object
                gps = new GPSTracker(MainActivity.this);

                // check if GPS location can get
                if (gps.canGetLocation()) {
                    Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
                } else {
                    // Can't get user's current location
                    gps.showSettingsAlert();
                    return;
                }

                new LoadPlaces().execute();
            }
        });
    }

    class LoadPlaces extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {
            Long t = Calendar.getInstance().getTimeInMillis();
            while (!gps.hasLocation && Calendar.getInstance().getTimeInMillis() - t < 60000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // get the places

            return null;
        }

        protected void onPostExecute(String file_url) {

            // dismiss the dialog after getting all products
            pDialog.dismiss();
            gps.stopUsingGPS();

            // display the results
        }
    }
}

update: I was thinking there might be a better option with a different thread, along the lines of what i wrote below. Or maybe with a service or a receiver.. Any ideas?

Thread th = new Thread() {
            boolean allEnabled = false;

            @Override
            public void run() {
                Long t = Calendar.getInstance().getTimeInMillis();
                while (!allEnabled && Calendar.getInstance().getTimeInMillis() - t < 120000) {
                    try {
                        isInternetPresent = cd.isConnectingToInternet();
                        if (!isInternetPresent) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please connect to a working Internet connection", false);
                                }
                            });
                        } else if (!gps.canGetLocation()) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    gps.showSettingsAlert();
                                }
                            });
                        } else {
                            allEnabled = true;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new LoadPlaces().execute();
                                }
                            });
                        }
                        Thread.sleep(20000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        th.start();

This version is of course not ok, since it spams one dialog after another.

KKO
  • 1,913
  • 3
  • 27
  • 35

2 Answers2

2

Usually something like this is solved through several callbacks/entrypoints in your activity. In order to do this you need to build your own AltertDialogs - one to prompt the user to enable internet and one to prompt the user to enable GPS. For the dialogs you will have to set the actions for the NegativeButton and the PositiveButton.

The logic would look something like this:

                                                               NegativeButton -> Exit App
                            Disabled -> Prompt user to enable {
OnCreate -> Check internet {                                   PositiveButton -> Go to Check GPS
                            |
                            |                                                          NegativeButton -> Exit App
                            |                       Disabled -> Prompt user to enable {
                            *-Enabled -> Check GPS {                                   PositiveButton -> Start AsyncTask
                                                    Enabled -> Start AsyncTask

You can implement the "Go to"'s as functions that are called in the OnClickListener of the PositiveButtons.

This is what makes Android a Callback-hell, but I have yet to find a better solution for stuff like this. I hope you can wrap your head around the concept!

ntv1000
  • 626
  • 6
  • 16
  • I already have the different alert dialogs built, only with positive buttons. The internet one displays "enable internet" and the button says OK, the gps one displays "enable location" and the button takes you to the gps settings screen. – KKO Jul 10 '14 at 12:26
  • That's a good start, now you need to stitch them together like illustrated in my ASCII flowchart. – ntv1000 Jul 10 '14 at 12:31
  • I will accept your answer, though I decided to keep the button and change the story around it. Seems less hassle this way – KKO Jul 16 '14 at 20:35
  • @K-RAD What I like doing is to make methods for the several "levels" of my setup. In your case that would be something like "startfrominternet" and "startfromgps". Then in OnCreate you would call startfrominternet and if that was successful you "go down" to the next level by calling "startfromgps" – ntv1000 Jul 16 '14 at 20:44
1

One way to do it, is to set the positive button of the alert dialog.

Put each into the positive button click of the alert dialog, such as follows:

    new AlertDialog.Builder(this)
            .setTitle("Problem")
            .setMessage(
                    "Please Check your *whatever is wrong* ")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    //Do the next activity

                    dialog.dismiss();
                }
            }).show();

If you want detailed code, then I will. Cheers!

Ra41P
  • 744
  • 1
  • 9
  • 18
  • I already have the different alert dialogs built, only with positive buttons. The internet one displays "enable internet" and the button says OK, the gps one displays "enable location" and the button takes you to the gps settings screen. – KKO Jul 10 '14 at 12:31
  • Well, then you're already ready to go :D I noticed that there is another answer, by ntv1000. He's put up a descriptive path to follow. Just add an onClick() to the positive button and keep working your way through the tree. Unless you want ready-made code. – Ra41P Jul 10 '14 at 12:36