hussein hammoud
hussein hammoud

Reputation: 385

Wifi State Check

I know this is a very frequent question but I've red all the repeated questions with no use :(
This is my code :

public class WifiFragment extends Fragment {

TextView tView ;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_wifi, container, false);

    Button  CheckWifibtn = (Button) rootView.findViewById(R.id.CheckWifi); 

    tView = (TextView) rootView.findViewById(R.id.textView5);

    CheckWifibtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckWifi();
        }
    });

    return rootView;
}


    public void CheckWifi() {
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (!wifi.isWifiEnabled()) {
        // wifi not enabled
        tView.setText("Wi-Fi is Disabled");
    }
    else {
        // wifi enabled
        tView.setText("Wi-Fi is Enabled");
    }
}

Please Guys Help me get the problem, I'm getting an error that getSystemService can't be resolved
I understand that i might need to add context somewhere in the code, but getContext and getApplicationContext aren't working either... I'm new at android programming so excuse my question :)

Upvotes: 0

Views: 51

Answers (1)

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

You need to use activity's context in Fragment. So you can use getActivity() for that.

public void CheckWifi() {
WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
if (!wifi.isWifiEnabled()) {
    // wifi not enabled
    tView.setText("Wi-Fi is Disabled");
}

Hope this helps.

Upvotes: 1

Related Questions