Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build a Weather App (2015) Concurrency and Error Handling What To Do When the Network is Down

Andrei Lorand
Andrei Lorand
7,322 Points

About the code challenge :)

Hello,

I love extra challenges because makes my mind work a bit and understand better all these concepts, as I am quite new to Android development. So what I actually wanted to do here was instead of having a Toast message in the "else" statement I tried to create a simple Dialog Fragment which will tell the user there's no internet connection and the option on the button to turn On the wifi. After googling around a bit I came out with this code:

public class AlertDialogWifi extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
            .setTitle("Error!")
            .setMessage("No internet connection")
            .setPositiveButton("Turn ON WiFI", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    turnOnWifi();
                }
            });
    AlertDialog dialog = builder.create();
    return dialog;
}
public void turnOnWifi() {
    Context context = getActivity();
    WifiManager wifi = (WifiManager)context.getApplicationContext().getSystemService(WIFI_SERVICE);
    if (wifi != null) {
        wifi.setWifiEnabled(true);
    }

} }

and on the MainActivity class, on the "else" statement I just did the conventional code we used on the alertUserAboutError() method:

else { //Toast.makeText(this, "No connection available", Toast.LENGTH_LONG).show(); AlertDialogWifi turnOnWifi = new AlertDialogWifi(); turnOnWifi.show(getFragmentManager(), "wifi_error"); }

The code works fine, or at least I ain't got any errors and the wifi was turned on once I pressed the button, but what I really want to ask: is there's a better and more efficient way to do that?

Thanks a ton and I looking forward for your feedback :)

1 Answer

Nataly Rifold
Nataly Rifold
12,431 Points

It looks great! But I wander if you found a way to reuse the AlertDialogFragment class instead of creating a new one. I have googled it and I can't find anything...