Android: Scanning Wifi Network + Selectable list
Asked Answered
C

2

7

I'm trying to creat an application that let you scan the available wifi networks, and then display them in a selectable list. To do that I tried with this code:

package android.nacho.WifiScan;

import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class WifiScan extends Activity {
    TextView mainText;
    WifiManager mainWifi;
    WifiReceiver receiverWifi;
    List<ScanResult> wifiList;
    StringBuilder sb = new StringBuilder();
    ListView listView = new ListView(this);
    ArrayAdapter<String> adapter;
    Context context = this;

    static String[] NETWORKS;

    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_wifi_scan);
       mainText = (TextView) findViewById(R.id.text);
       mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
       receiverWifi = new WifiReceiver();
       registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
       mainWifi.startScan();
       mainText.setText("\\nStarting Scan...\\n");


    }

    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "Refresh");
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        mainWifi.startScan();
        mainText.setText("Starting Scan");
        return super.onMenuItemSelected(featureId, item);
    }

    protected void onPause() {
        unregisterReceiver(receiverWifi);
        super.onPause();
    }

    protected void onResume() {
        registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        super.onResume();
    }

    class WifiReceiver extends BroadcastReceiver {
        public void onReceive(Context c, Intent intent) {


            wifiList = mainWifi.getScanResults();
            NETWORKS = new String[wifiList.size()];
            for(int i = 0; i < wifiList.size(); i++){

                NETWORKS[i]=i+"-"+(wifiList.get(i)).toString();


            }


            System.out.println("debería imprimir: "+NETWORKS[2]);


            adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_multiple_choice, NETWORKS);
            // adapter.setDropDownViewResource(android.R.layout.select_dialog_multichoice);
            listView.setAdapter(adapter);
            listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            listView.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {


                }

            });

            setContentView(listView);

        }
    }
}

But I'm getting this errors:

06-18 12:36:32.670: W/dalvikvm(15499): threadid=1: thread exiting with
uncaught exception (group=0x40dfb930)

06-18 12:36:32.670: E/AndroidRuntime(15499): FATAL EXCEPTION: main

 06-18 12:36:32.670: E/AndroidRuntime(15499):
java.lang.RuntimeException: Unable to instantiate activity
 ComponentInfo{android.nacho.WifiScan/android.nacho.WifiScan.WifiScan}:
 java.lang.NullPointerException

 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)

 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)

 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
 06-18 12:36:32.670: D/AndroidRuntime(15499): Shutting down VM 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 android.os.Looper.loop(Looper.java:137) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.app.ActivityThread.main(ActivityThread.java:5039) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 java.lang.reflect.Method.invokeNative(Native Method) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 java.lang.reflect.Method.invoke(Method.java:511) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 dalvik.system.NativeStart.main(Native Method) 06-18 12:36:32.670:
 E/AndroidRuntime(15499): Caused by: java.lang.NullPointerException
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.content.ContextWrapper.getResources(ContextWrapper.java:89)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.view.View.<init>(View.java:3224) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at android.view.View.<init>(View.java:3279)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.view.ViewGroup.<init>(ViewGroup.java:431) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.widget.AdapterView.<init>(AdapterView.java:235) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 android.widget.AbsListView.<init>(AbsListView.java:766) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 android.widget.ListView.<init>(ListView.java:143) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.widget.ListView.<init>(ListView.java:139) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.widget.ListView.<init>(ListView.java:135) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.nacho.WifiScan.WifiScan.<init>(WifiScan.java:27) 06-18
 12:36:32.670: E/AndroidRuntime(15499):     at
 java.lang.Class.newInstanceImpl(Native Method) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 java.lang.Class.newInstance(Class.java:1319) 06-18 12:36:32.670:
 E/AndroidRuntime(15499):   at
 android.app.Instrumentation.newActivity(Instrumentation.java:1054)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   at
 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
 06-18 12:36:32.670: E/AndroidRuntime(15499):   ... 11 more

What am I doing wrong??

Corenecoreopsis answered 18/6, 2013 at 10:54 Comment(3)
where did you tried it, an emulator or device?Admonish
I tried it in my handy: Samsung Galaxy Nexus, Android version 4.2. And in the manifest I added this three lines to get permissions: <uses-permission android:required="true" android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:required="true" android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission android:required="true" android:name="android.permission.INTERNET"/>Corenecoreopsis
The full logcat would definitely be helpful.Siliculose
A
17

Please try below one. Working well, but not tested properly. Please optimise the code yourself.

public class MainActivity extends Activity {


    WifiManager mainWifi;
    WifiReceiver receiverWifi;

    StringBuilder sb = new StringBuilder();

    private final Handler handler = new Handler();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        receiverWifi = new WifiReceiver();
        registerReceiver(receiverWifi, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        if (mainWifi.isWifiEnabled() == false) {
            mainWifi.setWifiEnabled(true);
        }


        doInback();
    }

    public void doInback() {
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

                if (receiveWifi == null)
                    receiverWifi = new WifiReceiver();
                registerReceiver(receiverWifi, new IntentFilter(
                        WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
                mainWifi.startScan();
                doInback();
            }
        }, 1000);

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "Refresh");
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        mainWifi.startScan();

        return super.onMenuItemSelected(featureId, item);
    }


    @Override
    protected void onPause() {
        unregisterReceiver(receiverWifi);
        super.onPause();
    }

    @Override
    protected void onResume() {
        registerReceiver(receiverWifi, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        super.onResume();
    }

    class WifiReceiver extends BroadcastReceiver {
        public void onReceive(Context c, Intent intent) {

            ArrayList<String> connections = new ArrayList<String>();
            ArrayList<Float> Signal_Strenth = new ArrayList<Float>();

            sb = new StringBuilder();
            List<ScanResult> wifiList;
            wifiList = mainWifi.getScanResults();
            for (int i = 0; i < wifiList.size(); i++) {

                connections.add(wifiList.get(i).SSID);
            }


        }
    }


}
Admonish answered 18/6, 2013 at 11:7 Comment(6)
Thanks for the reply, it looks like very nice, but there is some kind of error in the class "WifiReceiver": The type TestPreprationActivity.WifiReceiver must implement the inherited abstract method BroadcastReceiver.onReceive(Context, Intent)Corenecoreopsis
yes there is, u can see public void onReceive(Context c, Intent intent) method inside the WifiReceiver..Admonish
edit: problem solved. Thank you very much, the code is really usefulCorenecoreopsis
im new to android. how do i create a view showing these scan results? I create an object of this class and no window/results show.Bufford
This answer works, but you're doing a lot of extra work. You only need to get the wifi manager, create the wifi receiver, and register the receiver once. Pretty much the only thing that needs to be in the run function for this to work is mainWifi.startScan(); Also, I would just make the runnable a member variable and put postDelayed(this, 1000) at the end of the function. And call postDelayed(runnable) at the end of on create, so you're not creating the same Runnable over and over.Brickyard
I used this solution and it works well. But there is an unusual problem for me! When I install my application on a Samsung device it doesn't show any wifi! Why it's happening?Gastroenterology
A
3

Doesn't doInback() create multiple WifiReceivers which then will end up in an Exception as they might not all get unregistered?

Maybe s.th. like this could fix that:

if (receiveWifi==null) {
   receiveWifi = new WifiReceiver();
}
Adal answered 7/11, 2015 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.