Error connecting to the Internet

I am using volley to load my listview items. However, I don't know how to enable this code to show when there is an error in the internet connection before the download starts. Here is the piece of code I want to add:

if(isNetworkAvailable()) {

    /* DO WHATEVER YOU WANT IF INTERNET IS AVAILABLE */

    } else {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("No Internet");
        builder.setMessage("Internet is required. Please Retry.");

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });

        builder.setPositiveButton("Retry", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                InitiateDownload();
            }
        });
        AlertDialog dialog = builder.create(); // calling builder.create after adding buttons
        dialog.show();
        Toast.makeText(this, "Network Unavailable!", Toast.LENGTH_LONG).show();
    }

      

And here is my activity:

public class Movies extends ActionBarActivity{
    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Movies json url
    private static final String url = "http://api.androidhive.info/json/movies.json";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event);

     getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    Intent newActivity2=new Intent();
    setResult(RESULT_OK, newActivity2);

    listView = (ListView) findViewById(R.id.list);
    adapter = new CustomListAdapter(this, movieList);
    listView.setAdapter(adapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    // changing action bar color
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#1b1b1b")));

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("title"));
                            movie.setThumbnailUrl(obj.getString("image"));
                            movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);

                            // adding movie to movies array
                            movieList.add(movie);

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

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (error.networkResponse==null){
                     if (error.getClass().equals(TimeoutError.class)){
                         Toast.makeText(getBaseContext(), "Bummer.No Internet connection!", Toast.LENGTH_SHORT).show();

                }}}
            });

    // Adding request to request queue
ParseApplication.getInstance().addToRequestQueue(movieReq);
}

@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ 

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) { 

            Intent intent = new Intent(Movies.this, Detail.class);     
            startActivity(intent);
        }
        });}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}



    }

      

Is there a way to insert code into this activity, or is there another way? Thanks in advance guys.

+3


source to share





All Articles