Question

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 . 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:

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
Était-ce utile?

La solution

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. 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();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top