Issue
I tried to check the network connection in my SherlockFragment but the getSystemService() method is not recognized.
Below is my code (from http://developer.android.com/training/basics/network-ops/connecting.html)
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
} else {
// display error
}
Thanks in advance
Solution
The method getSystemService()
is not defined on fragments, so get the activity first using getActivity()
, e.g.:
ConnectivityManager connMgr = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
} else {
// display error
}
p.s: additianal note: if there is a potential risk that the fragment is running without being attached to any activity, check whether getActivity()
returns null
first.
Cheers!
Answered By - Trinimon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.