无法在ip地址mac地址上运行代码

时间:2017-02-13 20:17:15

标签: android nullpointerexception

我正在使用网络扫描仪,我发现了这段代码 但我无法找到问题所在 我有异常,如果有人可以帮忙调试这个,我们将不胜感激。

MainActivity

package com.example.george.droidscanner;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Button btnRead;
    TextView textResult;

    ListView listViewNode;
    ArrayList<Node> listNote;
    ArrayAdapter<Node> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnRead = (Button)findViewById(R.id.readclient);
        textResult = (TextView)findViewById(R.id.result);

        listViewNode = (ListView)findViewById(R.id.nodelist);
        listNote = new ArrayList<>();
        ArrayAdapter<Node> adapter =
                new ArrayAdapter<Node>(
                        MainActivity.this,
                        android.R.layout.simple_list_item_1,
                        listNote);
        listViewNode.setAdapter(adapter);

        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TaskReadAddresses(listNote, listViewNode).execute();
            }
        });
    }

    class Node {
        String ip;
        String mac;
        String CanonicalHostName;
        String HostName;
        String LocalHostCanonicalHostName;
        String LocalHostHostName;
        String remark;
        boolean isReachable;

        Node(String ip, String mac){
            this.ip = ip;
            this.mac = mac;
            queryHost();
        }

        @Override
        public String toString() {
            return "IP: " + ip + "\n" +
                    "MAC: " + mac + "\n" +
                    "CanonicalHostName:\t" + CanonicalHostName + "\n" +
                    "HostName:\t" + HostName + "\n" +
                    "getLocalHost().getCanonicalHostName():\t" + LocalHostCanonicalHostName + "\n" +
                    "getLocalHost().getHostName():\t" + LocalHostHostName + "\n" +
                    "isReachable: " + isReachable +
                    "\n" + remark;
        }

        private void queryHost(){
            try {
                InetAddress inetAddress = InetAddress.getByName(ip);
                CanonicalHostName = inetAddress.getCanonicalHostName();
                HostName = inetAddress.getHostName();
                LocalHostCanonicalHostName = inetAddress.getLocalHost().getCanonicalHostName();
                LocalHostHostName = inetAddress.getLocalHost().getHostName();
                isReachable = inetAddress.isReachable(3000);

            } catch (UnknownHostException e) {
                e.printStackTrace();
                remark = e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                remark = e.getMessage();
            }
        }
    }

    private class TaskReadAddresses extends AsyncTask<Void, Node, Void> {

        ArrayList<Node> array;
        ListView listView;

        TaskReadAddresses(ArrayList<Node> array, ListView v){
            listView = v;
            this.array = array;
            array.clear();
            textResult.setText("querying...");
        }

        @Override
        protected Void doInBackground(Void... params) {
            readAddresses();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            textResult.setText("Done");
        }

        @Override
        protected void onProgressUpdate(Node... values) {
            listNote.add(values[0]);
            ((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();
        }

        private void readAddresses() {
            BufferedReader bufferedReader = null;

            try {
                bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] splitted = line.split(" +");
                    if (splitted != null && splitted.length >= 4) {
                        String ip = splitted[0];
                        String mac = splitted[3];
                        if (mac.matches("..:..:..:..:..:..")) {
                            Node thisNode = new Node(ip, mac);
                            publishProgress(thisNode);
                        }
                    }
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

布局文件。

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    tools:context="com.example.george.droidscanner.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <Button
        android:id="@+id/readclient"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Read Ip/MAC addresses"/>

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:typeface="monospace"
        android:textSize="24sp"/>
</LinearLayout>

自定义适配器nodelist.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:id="@+id/nodelist"
    android:layout_height="match_parent">

</ListView>

运行时错误

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.george.droidscanner, PID: 2481
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.george.droidscanner/com.example.george.droidscanner.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                      at android.app.ActivityThread.access$800(ActivityThread.java:151)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5254)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                      at com.example.george.droidscanner.MainActivity.onCreate(MainActivity.java:43)
                      at android.app.Activity.performCreate(Activity.java:5990)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                      at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:135) 
                      at android.app.ActivityThread.main(ActivityThread.java:5254) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:372) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Application terminated.

2 个答案:

答案 0 :(得分:0)

  

自定义适配器nodelist.xml

这是你自己的问题。

setContentView(R.layout.activity_main);

findViewById来自activity_main.xml。那里根本没有ListView

您可以在activity_main

内尝试此操作
<include layout="@layout/nodelist" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

答案 1 :(得分:0)

您的布局文件不包含ListView。所以findViewById(R.id.nodelist)返回null并且您正在设置null对象的适配器,因此它会喊叫

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference