title: Android change wifi network not working
body: <p>I am trying to connect to a specific wifi network, as described <a href="https://stackoverflow.com/a/8818490/168175">here</a>. However, while sometimes it works, most of the times it doesn't. I do not really understand why if I run the app, let's say 10 times, the device connects to my network 2 times, and the other 8 it doesn't.</p>
  
  <p>In the following is the code I use in a Fragment.</p>
  
  <pre><code>WifiConfiguration wificonfiguration = new WifiConfiguration();
  wificonfiguration.SSID = "\"" + networkSSID + "\"";
  wificonfiguration.priority = 40;
  wificonfiguration.status = WifiConfiguration.Status.ENABLED;
  
  // WPA management
  wificonfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
  wificonfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
  wificonfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
  wificonfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
  wificonfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
  wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
  wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
  wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
  wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
  wificonfiguration.preSharedKey = "\"" + networkPass + "\"";
  
  WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
  
  int networkId = wifiManager.addNetwork(wificonfiguration);
  
  if (networkId &gt; -1) {
      boolean status = wifiManager.enableNetwork(networkId, true);
  }
  </code></pre>
  
  <p>The network configuration is actually added to the manager and <code>status</code> value is true. I have run it on several devices running Lollipop. Also, the network I want to connect to does not provide internet access, so I also thought that may be a problem for what stated in the note <a href="http://developer.android.com/reference/android/net/wifi/WifiManager.html#enableNetwork(int,%20boolean)" rel="nofollow noreferrer">here</a>. Can anybody tell me if the code is ok?</p>
  
  <p><strong>Solved</strong></p>
  
  <p>The problem was solved by adding <code>wifiManager.disconnect();</code> before adding the new network configuration.</p>