简体   繁体   English

空指针异常导致应用程序崩溃

[英]application crashing due to null pointer exception

I have created the instance of other class in send class and called the function of other class from the send class but it gives NPE . 我已经在send类中创建了其他类的实例,并从send类中调用了其他类的函数,但是它提供了NPE。 My send class from where I called the function of other class ,which is broadcast class and also this function is called when the button is clicked. 我的发送类是从我调用的其他类的函数(广播类)中获得的,单击按钮时也会调用此函数。

  broadcast broadcastobject.threadfunc(messages);

My class where I create threads is: 我创建线程的课程是:

  public class broadcast  {

private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";


public void threadfunc(String message){
    str=message;
                new Thread(new ClientThread()).start();
}

/*
 private InetAddress getBroadcastAddress() throws IOException {
        DhcpInfo dhcp = mWifi.getDhcpInfo();
        if (dhcp == null) {
          //Log.d(TAG, "Could not get dhcp info");
          return null;
        }

        int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
        byte[] quads = new byte[4];
        for (int k = 0; k < 4; k++)
          quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
        return InetAddress.getByAddress(quads);
      }

      */

class ClientThread implements Runnable {

    @Override
    public void run() {


        try {
            socket = new DatagramSocket(SERVERPORT);

            socket.setBroadcast(true);
    //              socket.setSoTimeout(TIMEOUT_MS);
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            InetAddress serverAddr = null;
            try {


                serverAddr = InetAddress.getByName(SERVER_IP);


            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

           packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);

            try {

                    socket.send(packet);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    } 

    }

}

My send.java is: 我的send.java是:

public class Send extends android.app.ListFragment  {

WifiManager mwifi; 
Button bt1;
boolean testwifi;
TextView tv1;
EditText et1;
String str1;
int id=1;
String messages;
private DataSource datasource;
broadcast broadcastobject;

void wifi() {
    mwifi=(WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);


    if(!mwifi.isWifiEnabled())
    {
        if(mwifi.getWifiState()!=WifiManager.WIFI_STATE_ENABLED)
            mwifi.setWifiEnabled(true);
    }

}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View rootView = inflater.inflate(R.layout.send, container, false);
    datasource = new DataSource(getActivity());
    datasource.open();

    List<Message> values = datasource.getAllMessages();

    // Use the SimpleCursorAdapter to show the
    // elements in a ListView
    ArrayAdapter<Message> adapter = new ArrayAdapter<Message>(getActivity(), android.R.layout.simple_list_item_1, values);
   setListAdapter(adapter);

    bt1=(Button)rootView.findViewById(R.id.button1);
    tv1=(TextView)rootView.findViewById(R.id.textView1);
    et1=(EditText)rootView.findViewById(R.id.editText1);

    bt1.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

             @SuppressWarnings("unchecked")
            ArrayAdapter<Message> adapter = (ArrayAdapter<Message>) getListAdapter();
                Message message = null;

            /*  ConnectivityManager cn= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);


    NetworkInfo networkInfo = cn.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
    testwifi=networkInfo.isConnected();
    if(!testwifi)
        tv1.setText("wifi is off");
    else
        tv1.setText("wifi is on");*/



                wifi();



                // Save the Data in Database
                messages=et1.getText().toString();

                // check if any of the fields are vaccant
                if(messages.equals(""))
                {
                                           Toast.makeText(getActivity().getApplicationContext(), "Field Vaccant",    Toast.LENGTH_LONG).show();
                        return;
                }
                else
                {

                     message = datasource.createMessage(messages);
                      adapter.add(message);

                // broadcastobject=new broadcast(messages);
                //broadcastobject.start();

                      broadcastobject.threadfunc(messages);

                      et1.setText("");
                }



                  adapter.notifyDataSetChanged();
        }

    });



    return rootView;


}
/*public class MyLocationListener implements LocationListener
{

public void onLocationChanged(Location loc)

{

loc.getLatitude();

loc.getLongitude();
String Text = "My location is: " +

"Latitude = " + loc.getLatitude() +

"Longitude = " + loc.getLongitude();

//finish();


Toast.makeText( getActivity().getApplicationContext(),Text,Toast.LENGTH_SHORT).show();

}


public void onProviderDisabled(String provider)

{

Toast.makeText(getActivity(). getApplicationContext(),"GPS Disabled",Toast.LENGTH_SHORT ).show();

}


public void onProviderEnabled(String provider)

{

Toast.makeText( getActivity().getApplicationContext(),"GPS Enabled",Toast.LENGTH_SHORT).show();

}



@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}

     }*/
@Override
public void onResume() {
    datasource.open();
    super.onResume();
  }

  @Override
public void onPause() {
    datasource.close();
    super.onPause();
  }


    }

My log cat is: 我的日志猫是:

09-01 17:35:50.350: D/gralloc_goldfish(3557): Emulator without GPU emulation detected.
 09-01 17:36:10.300: D/AndroidRuntime(3557): Shutting down VM
09-01 17:36:10.309: W/dalvikvm(3557): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
 09-01 17:36:10.369: E/AndroidRuntime(3557): FATAL EXCEPTION: main
 09-01 17:36:10.369: E/AndroidRuntime(3557): java.lang.NullPointerException
  09-01 17:36:10.369: E/AndroidRuntime(3557):   at soft.b.peopleassist.Send$1.onClick(Send.java:114)
  09-01 17:36:10.369: E/AndroidRuntime(3557):   at android.view.View.performClick(View.java:3480)
  09-01 17:36:10.369: E/AndroidRuntime(3557):   at android.view.View$PerformClick.run(View.java:13983)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at android.os.Handler.handleCallback(Handler.java:605)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at android.os.Handler.dispatchMessage(Handler.java:92)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at android.os.Looper.loop(Looper.java:137)
09-01 17:36:10.369: E/AndroidRuntime(3557):     at android.app.ActivityThread.main(ActivityThread.java:4340)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at java.lang.reflect.Method.invokeNative(Native Method)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at java.lang.reflect.Method.invoke(Method.java:511)
09-01 17:36:10.369: E/AndroidRuntime(3557):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
 09-01 17:36:10.369: E/AndroidRuntime(3557):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-01 17:36:10.369: E/AndroidRuntime(3557):     at dalvik.system.NativeStart.main(Native Method)
   09-01 17:36:13.150: I/Process(3557): Sending signal. PID: 3557 SIG: 9

You are receiving null pointer because you haven't created any object of class broadcast and are trying to call the function present in that class. 您正在接收null指针,因为尚未创建任何broadcast类的对象,并试图调用该类中存在的函数。 Since the function is not static you cannot use it without using an object of that class. 由于该函数不是静态的,因此如果不使用该类的对象,就无法使用它。 So, first you need to create an object before calling the function like: 因此,首先需要在调用以下函数之前创建一个对象:

broadcast broadcastobject = new broadcast();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM