Android_Developer
Android_Developer

Reputation: 481

How to handle internet availability for this code

In My Application i am parsing the feed from the net as like below code:

private void downloadEpisodes(String Url) {
    //Make Progress Bar Visible While Downloading Feed
    progress_bar.setVisibility(ProgressBar.VISIBLE);
    Log.d("CGRParser", "Downloading Feed");
    //Start an ASync Thread to take care of Downloading Feed
    new DownloadEpisodes().execute(Url);
}

private class DownloadEpisodes extends AsyncTask<String, Integer, ArrayList<LatestNews>> {
    ArrayList<LatestNews> episodes;
    @Override
    protected ArrayList<LatestNews> doInBackground(String... url) {

        //Download and Parse Feed
        XmlFeedParser parser = new XmlFeedParser();
        episodes = new ArrayList<LatestNews>();
        episodes = parser.parse(url[0]);
        return episodes;
    }

    @Override
    protected void onPostExecute(ArrayList<LatestNews> result) {
        //Feed has been Downloaded and Parsed, Display Data to User
        Log.d("CGRParser", "Feed Download Complete");
        displayEpisodes(result);
    }
}

private void displayEpisodes(ArrayList<LatestNews> news_detail) {
    //Create String Arrays to seperate titles and dates
    Log.d("CGRParser", "Displaying News Titles To User");
    ArrayList<String> episode_titles = new ArrayList<String>();
    ArrayList<String> episode_description = new ArrayList<String>();
    ArrayList<String> episode_link = new ArrayList<String>();
    for (LatestNews news : news_detail) {
        Log.d("News", "News Title: " + news.getTitle());
        Log.d("News", "News Description: " + news.getDescription());
        Log.d("News", "News Link: " + news.getLink());
        episode_titles.add(news.getTitle());
        episode_description.add(news.getDescription());
        episode_link.add(news.getLink());
    }

    this.episode_titles = episode_titles;
    this.episode_description = episode_description;
    this.episode_link = episode_link;

    //Create a ListAdapter to Display the Titles in the ListView
    ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.latest_news_row, R.id.title, episode_titles);
    listview_news.setAdapter(adapter);
    //Set Progress Bar Invisible since we are done with it
    progress_bar.setVisibility(ProgressBar.INVISIBLE);

}

Now with this code i want to handle the internet availability. If internate is not available then the Message should be dispaly like "Please check the internate connection."

Please help me for this. Thanks.

Upvotes: 0

Views: 181

Answers (2)

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53657

How to check network availability

public static boolean isNetworkPresent(Context context) {
        boolean isNetworkAvailable = false;
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        try {

            if (cm != null) {
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null) {
                    isNetworkAvailable = netInfo.isConnectedOrConnecting();
                }
            }
        } catch (Exception ex) {
            Log.e("Network Avail Error", ex.getMessage());
        }
        //check for wifi also
        if(!isNetworkAvailable){
            WifiManager connec = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            State wifi = cm.getNetworkInfo(1).getState();
            if (connec.isWifiEnabled()
                    && wifi.toString().equalsIgnoreCase("CONNECTED")) {
                isNetworkAvailable = true;
            } else {

                isNetworkAvailable = false;
            }

        }
        return isNetworkAvailable;
    }

Upvotes: 1

Michał Klimczak
Michał Klimczak

Reputation: 13154

You have to put network state permission in your manifest.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Then you can check if the connection is available with a function like this one (someone posted it eralier in stackoverflow and I use it in my app):

    public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

And then you simply check if isOnline in your activity and show a Toast or other dialog if it's not. And I think you should do the check in your activity before task.execute(), not in the AsyncTask.

Upvotes: 2

Related Questions