Click here to Skip to main content
15,301,414 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
Hello, I want to send udp packets by wifi. I use below code.
But I get error in LogCat: error message in sending null

BroadcastThread.java:
public class BroadcastThread extends Thread{
	
	final static private String TAG = "Chat";
	final static boolean D = true;
	final static int PORT = 6666;
	
	boolean okbroadcast=false;

	Handler 		mHandler;      // Handler for messages in the main thread 
	Context 		mContext;	   // Context to the application (for getting ip Addresses)
	DatagramSocket 	serverSocket;  // Socket used both for sending and receiving 
	static public boolean 		socketOK=true; // True as long as we don't get socket errors
	
	InetAddress 	myBcastIPAddress; 		// my broadcast IP addresses
	InetAddress 	myIPAddress; 	
	
	
	public BroadcastThread(Context currentContext,	Handler handler)
	{
		mContext = currentContext;
		mHandler = handler;
		
		try{ // Let's open an UDP socket - we'll receive the messages on this socket
			serverSocket = new DatagramSocket(PORT);
			serverSocket.setBroadcast(true);
			Log.i(TAG,"server sicket is created.");
		} catch(Exception e){
			Log.e(TAG,"Cannot open socket! "+e.getMessage());
			socketOK = false;
			return;
		}
		
		try{
			getMyWiFiBcastAndIPAddress();
			Log.i(TAG,"My IP address:"+myIPAddress);
			Log.i(TAG,"My Broadcast IP address:"+myBcastIPAddress);
		}catch(Exception e){
			Log.e(TAG,"Cannot get my own Broadcast IP address");
		}
	}
	
	

	// Method for closing the socket before exiting application
	public void closeSocket(){
		serverSocket.close();
	}
	
	
	// If the socket is OK, then it's running
	boolean socketIsOK(){
	  return socketOK;
	}
	
	public void run(){
			
			if (okbroadcast==true)
				mHandler.obtainMessage(1,okbroadcast).sendToTarget();
if(!socketOK)
				closeSocket();
			
		}// end run()

		
		
		// Sends an UDP packet at the broadcast address
		public void sendMessage(String msg) throws IOException {
			
			Log.i(TAG,"string in thread= "+msg);
			
			byte[] sendData  = new byte[1024]; 

			sendData = msg.getBytes(); 
			
			Log.i(TAG,"to byte[] in thread= "+sendData);

			DatagramPacket sendPacket = 
				new DatagramPacket(sendData, sendData.length, myBcastIPAddress, PORT); 
			
			Log.i(TAG,"byte[] length in thread= "+sendData.length);
			
			
			if(sendData==null)
				Log.i(TAG,"sendData is null! "+sendData);
			
			
			if(serverSocket==null)
				Log.i(TAG,"serversocket is null! "+serverSocket);

			serverSocket.send(sendPacket);
			
			Log.i(TAG,"after sending........ ");
			okbroadcast=true;
	        Log.i(TAG,"Sent packet: "+msg);
	        
	        closeSocket();

		}
		
		
		
		private void getMyWiFiBcastAndIPAddress() throws UnknownHostException{

	        WifiManager mWifi = (WifiManager) (mContext.getSystemService(Context.WIFI_SERVICE));
	        WifiInfo info = mWifi.getConnectionInfo();
	        if(info==null){
	            if(D) Log.e(TAG,"Cannot Get WiFi Info");
	            return;
	        }
	        else{
	        	if(D) Log.d(TAG,"\n\nWiFi Status: " + info.toString());
	        }
			  
	  	  // DhcpInfo  is a simple object for retrieving the results of a DHCP request
	        DhcpInfo dhcp = mWifi.getDhcpInfo(); 
	        if (dhcp == null) { 
	          Log.d(TAG, "Could not get dhcp info"); 
	          return; 
	        } 


	        int myIntegerIPAddress = dhcp.ipAddress;

	        byte[] quads = new byte[4]; 
	        for (int k = 0; k < 4; k++) 
	           quads[k] = (byte) ((myIntegerIPAddress>> k * 8) & 0xFF);

	        myIPAddress = InetAddress.getByAddress(quads);

	        
	        int myIntBroadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; 
	        for (int k = 0; k < 4; k++) 
	          quads[k] = (byte) ((myIntBroadcast >> k * 8) & 0xFF);
	        
	        // Returns the InetAddress corresponding to the array of bytes. 
	        myBcastIPAddress=InetAddress.getByAddress(quads); 
	    	
	    }
	    	
		

}




and in activity Directory.java:

public class Directory extends Activity {
	
	Utility ut=new Utility();
	BroadcastThread 	broadThread;
	ArrayAdapter	<String>receivedMessages;
	
	
	
	private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
	            
	                String incomingMessage = (String) msg.obj;
	                Toast.makeText(getApplicationContext(), "in hendler: "+incomingMessage, Toast.LENGTH_LONG).show();
	                Log.i("vote", "in hendler: "+incomingMessage);
	                
	                if(!incomingMessage.matches(""))   
	                {
	                	BroadcastThread.socketOK=false;
	                }
            
        }
    };    
	
	
	
	//Events
		btn_create_session.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			
				
				
				// Start my server thread
		        broadThread = new BroadcastThread(getApplicationContext(),mHandler);

		        //Check if it's running
		        if (!broadThread.socketIsOK()){
		     	   Log.e("vote","Server NOT STARTED");
		     	   Toast.makeText(getApplicationContext(), "Cannot Start Server ", Toast.LENGTH_LONG).show();
		     	   return;
		         }

		        // All appears to be OK, start the main loop
		        broadThread.start();
		         Log.i("vote","Server Started");
		        
		        
		         try{
		        	
		     		broadThread.sendMessage("namekey");
		     		
		     		 
		     	}catch(Exception e){
		     		Toast.makeText(Directory.this, "Cannot send message"+e.getMessage(), Toast.LENGTH_LONG).show();
		     		Log.e("vote","error message in sending: "+e.getMessage());
		     	}
		     	
		     	finally{
		     		broadThread.closeSocket();
		     	}
				
			}
		});
Posted
Comments
Richard MacCutchan 25-Jul-15 10:01am
   
"I get error in LogCat: error message in sending null"
Where in the code?
suraty 25-Jul-15 10:49am
   
in Directory.java before finally in catch there is Log.e("vote","error message in sending: "+e.getMessage());
I try broadThread.sendMessage("namekey");
Richard MacCutchan 25-Jul-15 11:44am
   
Then it looks like you have not initialised the broadThread variable. Check your code and use your debugger to find out why.
suraty 25-Jul-15 12:04pm
   
I have this lines:
BroadcastThread broadThread;
// Start my server thread
broadThread = new BroadcastThread(getApplicationContext(),mHandler);
In directory.java.
Richard MacCutchan 25-Jul-15 12:10pm
   
See my Solution comments below.

1 solution

In BroadCastThread you have the following:
Java
if(serverSocket==null)
    Log.i(TAG,"serversocket is null! "+serverSocket);

serverSocket.send(sendPacket);

But if serverSocket is null the last line will cause a NullReference exception.
   
Comments
suraty 25-Jul-15 12:13pm
   
I don't see "serversocket is null!" In my LogCat. What will make null exception?
Richard MacCutchan 25-Jul-15 12:25pm
   
Could be anything but you will need to use your debugger to find out what. It is impossible to guess just from looking at the code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900