0

Пытаюсь сделать простое приложение для работы с wifi сетями, одной из частей которого должен быть сканер wifi сетей. Изначально сделал также, как было отвечено здесь: https://stackoverflow.com/questions/5452940/how-can-i-get-android-wifi-scan-results-into-a-list

Данный код успешно работал на моем тестовом устройстве. Далее решил отделить функционал сканирования от "основного" и вынести все элементы интерфейса в Main. После чего на том же самом тестовом устройстве приложение начало падать с выводом: "приложение wifi_demo.xml остановлено". В андроиде новичок, никак не могу выяснить, что сделал не так.

Лог об ошибке:

   08-20 13:11:40.216 18683-18683/com.example.lazm.helloapp I/System.out: debugger has settled (1466)
   08-20 13:11:40.236 18683-18683/com.example.lazm.helloapp I/PersonaManager: getPersonaService() name persona_policy
   08-20 13:11:40.436 18683-18683/com.example.lazm.helloapp D/AbsListView:   Get MotionRecognitionManager
   08-20 13:11:40.457 18683-18683/com.example.lazm.helloapp D/AndroidRuntime: Shutting down VM
   08-20 13:11:40.457 18683-18683/com.example.lazm.helloapp W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x418abda0)
   08-20 13:11:40.467 18683-18683/com.example.lazm.helloapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lazm.helloapp, PID: 18683
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lazm.helloapp/com.example.lazm.helloapp.Main}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2412)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
          at android.app.ActivityThread.access$900(ActivityThread.java:174)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:146)
          at android.app.ActivityThread.main(ActivityThread.java:5593)
          at java.lang.reflect.Method.invokeNative(Native Method)
          at java.lang.reflect.Method.invoke(Method.java:515)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
          at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
          at android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93)
          at android.widget.ListView.setAdapter(ListView.java:486)
          at com.example.lazm.helloapp.Main.onCreate(Main.java:37)
          at android.app.Activity.performCreate(Activity.java:5458)
          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470) 
          at android.app.ActivityThread.access$900(ActivityThread.java:174) 
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307) 
          at android.os.Handler.dispatchMessage(Handler.java:102) 
          at android.os.Looper.loop(Looper.java:146) 
          at android.app.ActivityThread.main(ActivityThread.java:5593) 
          at java.lang.reflect.Method.invokeNative(Native Method) 
          at java.lang.reflect.Method.invoke(Method.java:515) 
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
        at dalvik.system.NativeStart.main(Native Method) 

Код:

Main.java:

public class Main extends Activity implements View.OnClickListener
{
    ListView lv;
    TextView textStatus;
    Button buttonScan;
    SimpleAdapter adapter;
    ArrayList<HashMap<String, String>> arraylist;

    private String ITEM_KEY = "key";

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

        textStatus = (TextView) findViewById(R.id.textStatus);
        buttonScan = (Button) findViewById(R.id.buttonScan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.list);
        this.adapter = new SimpleAdapter(this, arraylist, R.layout.row, new         
String[] { ITEM_KEY }, new int[] { R.id.list_value });
        lv.setAdapter(this.adapter);
    }

    public void onClick(View view)
    {
        arraylist.clear();
        WiFiDemo demo = new WiFiDemo(this);
        arraylist = demo.getNetworksList();
        adapter.notifyDataSetChanged();
    }
}

WiFiDemo.java:

public class WiFiDemo 
{
    private Context context;
    private WifiManager wifi;
    private int size = 0;
    private List<ScanResult> results;

    private String ITEM_KEY = "key";
    private ArrayList<HashMap<String, String>> arraylist = new     
ArrayList<HashMap<String, String>>();

    public WiFiDemo()
    {

    }

    public WiFiDemo(Context context)
    {
        this.context = context;
        wifi = (WifiManager)      
this.context.getSystemService(Context.WIFI_SERVICE);

        this.context.registerReceiver(new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context c, Intent intent)
            {
                results.clear();
                results = wifi.getScanResults();
                size = results.size();
            }
        }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }

    public ArrayList<HashMap<String, String>> getNetworksList()
    {
        ArrayList<HashMap<String, String>> result = new 
ArrayList<HashMap<String, String>>();

        if (!wifi.isWifiEnabled())
        {
            Toast.makeText(context, "Activating WiFi", 
Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }

        wifi.startScan();

        // Wait for broadcast reply

        getNetworksFromBroadcastReply();

        return arraylist;
    }

    private void getNetworksFromBroadcastReply()
    {
        arraylist.clear();

        Toast.makeText(this.context, "Scanned: [" + size + "] networks 
available", Toast.LENGTH_SHORT).show();

        try
        {
            size = size - 1;
            while (size >= 0)
            {
                HashMap<String, String> item = new HashMap<String, String>();
                item.put(ITEM_KEY, results.get(size).SSID + "  " + 
results.get(size).capabilities);

                arraylist.add(item);
                size--;
            }
        }
        catch (Exception e)
        {
            Toast.makeText(context, "Scan error",Toast.LENGTH_SHORT).show();
        }
    }
}

wifi_demo.xml:

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textStatus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Status" />

        <Button
            android:id="@+id/buttonScan"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="Scan" />
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp"></ListView>
</LinearLayout>

row.xml:

    <TextView
        android:id="@+id/list_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="14dp" />
    </LinearLayout>

Файл манифеста:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lazm.helloapp">
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="wifi_demo.xml"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name="com.example.lazm.helloapp.Main"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</manifest>
4
  • почему не удалось получить стектрейс? если приложение аварийно остановлено, в логкат будет подробный лог о ошибке в любом случае. Без лога ошибки это гадание на кофейной гуще, мало кто таким любит заниматься
    – pavlofff
    20 авг 2018 в 10:06
  • Все таки смог найти лог, правда он не очень продвинул меня в понимании причины. Добавил в вопрос 20 авг 2018 в 10:19
  • Ошибка в 37-й строке Main.java - научитесь хотя бы логи читать что ли...
    – Barmaley
    20 авг 2018 в 10:25
  • Возможный дубликат вопроса: Что такое Null Pointer Exception и как его исправить? 20 авг 2018 в 10:33

1 ответ 1

2

Вы в адаптер arraylist передаёте:

this.adapter = new SimpleAdapter(this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });

Но arraylist не проинициализировали, там null.

В SimpleAdapter у вас где-то в коде берётся arraylist.count(), и оно падает.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.