-2

I want to display an alert message when Internet connection is not available in my android project. My Activity class loads a list-view through Internet and if the devices doesn't have an Internet connection it simply displays the activity. I want to show a toast or a prompt that your device doesn't have Internet connection.

here is my activity class:

      public class MainActivity2 extends AppCompatActivity {

    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String TAG_TITLE = "title";
    private static final String TAG_RATING = "rating";
    private Toolbar mToolbar;

    private FloatingActionButton fab;

    // Movies json url
    private static final String url =       "http://groupdiscount.netne.net/android_connect/movie.json";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        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();


        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity2.this, Register.class);
                startActivity(intent);
            }
        });


        // Listview on item click listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting values from selected ListItem
                String title = ((TextView) view.findViewById(R.id.title))
                        .getText().toString();
                String rating = ((TextView) view.findViewById(R.id.rating))
                        .getText().toString();


                // Starting single activity
                Intent in = new Intent(getApplicationContext(),
                        SingleActivity.class);
                in.putExtra(TAG_TITLE, title);
                in.putExtra(TAG_RATING, rating);
                startActivity(in);

            }
        });

        // 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) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

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


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

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}
Ali Khaki
  • 1,184
  • 1
  • 13
  • 24

1 Answers1

1
public boolean isOnline() {
    boolean result;
    ConnectivityManager cm =   (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()){
        result=true;
    }
    else{
        Toast.makeText(getBaseContext(), "Not Online",7000).show();
        result=false;
    }
    return result;
}

and use it as following:

if(isOnline()){
    loadListView(); // This would be the method that you load listview
}
Sufian
  • 6,405
  • 16
  • 66
  • 120
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82
  • Please tell me where to add this code in my activity.. – Nikhil Singh Feb 07 '16 at 16:35
  • Place this method at the end of your activity (before closing bracket which is not presented in your question). Before you load the ListView (I don't know when and how do you do that), I have added a simple code to the answer to show how to run your code. – Ali Sheikhpour Feb 07 '16 at 22:50