Loading...
Logo
Processing Forum
I am trying to connect to a wifi network programatically but my application crashes with the following error:

Copy code
  1. FATAL EXCEPTION: Animation Thread
  2. java.lang.NullPointerException
  3. at processing.test.sketch_130903a.sketch_130903a.connect_to_wifi(sketch_130903a.java:54)
  4. at processing.test.sketch_130903a.sketch_130903a.setup(sketch_130903a.java:75)
  5. at processing.core.PApplet.handleDraw(Unknown Source)
  6. at processing.core.PGraphicsAndroid2D.requestDraw(Unknown Source)
  7. at processing.core.PApplet.run(Unknown Source)
  8. at java.lang.Thread.run(Thread.java:1019)
Here is the code that I used (the SSID and password were removed)

Copy code
  1. import android.net.wifi.*;
  2. import android.content.*;
  3. import java.util.*;

  4. Context context;

  5. void connect_to_wifi(){
  6.   
  7.   //create wifi connection
  8.         String networkSSID = "";
  9.         String networkPass = "";

  10.         WifiConfiguration conf = new WifiConfiguration();
  11.         conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes

  12.          //For WPA network you need to add passphrase like this:

  13.             conf.preSharedKey = "\""+ networkPass +"\"";

  14.         //Then, you need to add it to Android wifi manager settings:
  15.         WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); 
  16.         wifiManager.addNetwork(conf);
  17.         
  18.         //And finally, you might need to enable it, so Android conntects to it:
  19.         List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
  20.         for( WifiConfiguration i : list ) {
  21.             if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
  22.                  wifiManager.disconnect();
  23.                  wifiManager.enableNetwork(i.networkId, true);
  24.                  wifiManager.reconnect();               

  25.                  break;
  26.             }           
  27.          }
  28. }

  29. void setup() {
  30.   size(480,800);
  31.   noStroke();
  32.   fill(255);
  33.   rectMode(CENTER);     // This sets all rectangles to draw from the center point
  34.   connect_to_wifi();
  35. }

  36. void draw() {
  37.   background(#FF9900);
  38.   rect(width/2, height/2, 150, 150);
  39. }

In the sketch properties the permissions for ACCESS_WIFI_STATE and CHANGE_WIFI_STATE are set.

Any sugestions on where is the problem?

Thanks