Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Weather App (2015) Concurrency and Error Handling Building an Alert Dialog

Ramesh Ram
Ramesh Ram
3,340 Points

use AlertDialogFragment. switch to the activity file and create and show a new AlertDialogFragment in the onFailure()

need help

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

You need to create a new instance of AlertDialogFragment. Then call the show() method on the instance and pass in getFragmentManager() and the message:

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;

public class MovieActivity extends Activity {

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

        // Get some movie information!
        String apiUrl = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=xyz&q=hobbit";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(apiUrl)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
              AlertDialogFragment dialog = new AlertDialogFragment();
              dialog.show(getFragmentManager(), "error_dialog");
            }

            @Override
            public void onResponse(Response response) throws IOException { }
        });
    }
}
import android.content.Context;
import android.os.Bundle;

public class AlertDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Context context = getActivity();

        // Insert code here!
        AlertDialog.Builder builder= new AlertDialog.Builder(context);
        builder.setTitle("Sorry!")
               .setMessage("Try again!")
               .setPositiveButton("OK", null); 

        return builder.create();
    }
}