Check network connection in fragment
Solution 1
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!
Solution 2
The better way is to use network function code in try- catch. And catch the exception If network unavailable. If you use any network checking code, then also you need to catch the exception. Because You have no other way to check whether it is suceeded or no, means, if the network lost in between the function completes.
Comments
-
Lalith Mohan almost 2 years
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
-
Lalith Mohan about 11 yearsIt Worked!! Thank you so much.
-
Jithu about 11 yearsI was searching the same way in first time, finaly i reached in this decesition. I simply shared with you.
-
Lalith Mohan about 11 yearsThe fragment is attached to an activity. What is the risk if not attached?
-
Trinimon about 11 yearsIf it is not attached,
getActivity()
might returnnull
and consequentlygetActivity().getSystemService()
throws aNullPointerException
. However, it depends where you call this code and how you create the fragments. Nothing to worry about, just keep it in your mind ;) -
Qadir Hussain about 10 years@Trinimon Im getting getActivity() null. how to resolve this? In android phone Running andriod 4.0.3 its working fine. but in tablet Nexus 7 running 4.4.1 it returns null. Whats going wrong. y its happing?
-
Trinimon about 10 yearsIf
getActivity()
returnsnull
, this shows that no activity has been attached at that point of time. Did you use it inonActivityCreated()
or somewhere else? Did you create the fragment solely? You can also try to move your code to theonAttach(Activity activity)
method of the fragment - here you have the activity available and you don't need to callgetActivity()
at all.