[Q] Socket code throws NullPointerException in OnsensorChanged

Search This thread

flavglen

Member
Feb 7, 2014
7
0
Hi frends im working on my android final year project based on sockets..im using ssynctask to connect socket etc..Everything works fine, since I'm using AsyncTask to create a Socket connection ... the socket works fine in the doInBackground() method, but when I try to send Sensor data from theonSensorChanged() method, I get null pointer exception. I don't know what went wrong. in short Socket returns NULL outside asyncTask Class...can some 1 help me ?..


here is my code
Code:
package com.example.sensorsmart;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener{


private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private   TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mAccelerometer mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);   
mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);

}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);}

private class MyTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... arg0) {

try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}

final  String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
} 
});

} catch (IOException e) {
e.printStackTrace();
String  response = e.getCause().toString();
Log.i("TCP",response);
}
return null;
}

}


@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
pw.write("g");  //NULL POINT EXCEPTION THROWS HERE
}
}

LOGCAT:

Code:
02-06 11:31:54.250: E/AndroidRuntime(4108): FATAL EXCEPTION: main
02-06 11:31:54.250: E/AndroidRuntime(4108): java.lang.NullPointerException
02-06 11:31:54.250: E/AndroidRuntime(4108):     at    com.example.sensorsmart.MainActivity.onSensorChanged(MainActivity.java:196)
02-06 11:31:54.250: E/AndroidRuntime(4108):     at     android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
02-06 11:31:54.250: E/AndroidRuntime(4108):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-06 11:31:54.250: E/AndroidRuntime(4108):     at android.os.Looper.loop(Looper.java:137)
02-06 11:31:54.250: E/AndroidRuntime(4108):     at android.app.ActivityThread.main(ActivityThread.java:4759)
02-06 11:31:54.250: E/AndroidRuntime(4108):     at java.lang.reflect.Method.invokeNative(Native Method)
02-06 11:31:54.250: E/AndroidRuntime(4108):     at java.lang.reflect.Method.invoke(Method.java:511)
02-06 11:31:54.250: E/AndroidRuntime(4108):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
02-06 11:31:54.250: E/AndroidRuntime(4108):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
02-06 11:31:54.250: E/AndroidRuntime(4108):     at dalvik.system.NativeStart.main(Native Method)
 

warlock9_0

Member
Apr 22, 2013
35
9
Athens
you have to set the variable in onpostexecute() and also use
Code:
new MyTask().execute().get()
so you make sure the async task has finished for sure
 

warlock9_0

Member
Apr 22, 2013
35
9
Athens
forget the execute().get() for now, maybe it is not needed

read the documents for asynctask and change your result type from void, to whatever you want to set
for example if you want only the PrintWriter to be set you can do this

Code:
package com.example.sensorsmart;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener{


private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private   TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	new MyTask().execute();
	mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
	mAccelerometer mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);   
	mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
	mSensorManager.unregisterListener(this);}

private class MyTask extends AsyncTask<Void, Void, PrintWriter>
{
	@Override
	protected PrintWriter doInBackground(Void... arg0) {

		try {
			serverSocket = new ServerSocket(8222);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			socket=serverSocket.accept();
			Log.i("TcpServer", "CONNECTED");
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			pw = new PrintWriter(socket.getOutputStream(),true);
			if(!in.ready())
			{
			Log.i("TcpServer", "READER IS NOT READY");
			}

			final  String g;
			final String c;
			String b = null;
			Log.i("TcpServer", "GOING");
			g=in.readLine();
			runOnUiThread(new Runnable() {
			public void run() {
			Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
			} 
			});

		} catch (IOException e) {
			e.printStackTrace();
			String  response = e.getCause().toString();
			Log.i("TCP",response);
		}
		return pw;
		}
		
		protected void onPostExecute(PrintWriter result) {
			pw = result;
		}  
}


@Override
public void onSensorChanged(SensorEvent event) {
	float x = event.values[0];
	float y = event.values[1];
	float z = event.values[2];
	if(pw!=null) pw.write("g");  //NULL POINT EXCEPTION THROWS HERE
}
}

if you want other variables to be returned too, you can make a custom object as the type of the result
 

flavglen

Member
Feb 7, 2014
7
0
is it possible to pass socket instead mof printwriter?

hi friend thank u for ur reply...is it possible to pass socket in onpostexecute () ?

i tried with below code still socket is null in ONsensor Changed
Code:
private class MyTask extends AsyncTask<Void, Void,Socket>

	{

	@Override
	protected Socket doInBackground(Void... arg0) {
		// TODO Auto-generated method stub
		
		
		 
		 
		 try {
			serverSocket = new ServerSocket(8222);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		 try {
			socket=serverSocket.accept();
			
			Log.i("TcpServer", "CONNECTED");
			
			
			 
             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
             pw = new PrintWriter(socket.getOutputStream(),true);
            
           //out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        
             
             if(!in.ready())
            {
            	Log.i("TcpServer", "READER IS NOT READY");
            }
          
           final  String g;
           final String c;
           
            String b = null;
            
            
        	Log.i("TcpServer", "GOING");
           
        	g=in.readLine();
        	
			//Log.i("TcpServer", in.readLine());
        	
        	  runOnUiThread(new Runnable() {
     	         public void run() {
     	        	
     	        	 
     	            Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
     	           
     	            
     	      } 
     	     });
     	      
			
			Log.i("TcpServer", "RECEIVED");
			
		
	
      	  runOnUiThread(new Runnable() {
   	         public void run() {
   	        	
   	        	 
   	            Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
   	           
   	            
   	      } 
   	     });
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			 String  response = e.getCause().toString();
			 
			 Log.i("TCP",response);
		}
	

		 
		return socket;
	}
		
	protected void onPostExecute(Socket result) {
		socket = result;
		
	
	}
 
Last edited:

warlock9_0

Member
Apr 22, 2013
35
9
Athens
yes, you can pass the socket like you do

but in the onsensorchanged function you are using the printwriter (pw) you created in the doinbackground function which is null because you haven't passed it to the main thread

so, you either have to make a new object that will pass all the things to the main threat (socket, printwriter, bufferedreader) if you want them all, or pass the printwriter only, or you will initialize them on the post execute function

for example, you can return the socket and then do

Code:
protected void onPostExecute(Socket result) {
		socket = result;
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		pw = new PrintWriter(socket.getOutputStream(),true);

	}
 
Last edited:

flavglen

Member
Feb 7, 2014
7
0
still null

here is my entire code..i have done exactly what u said...still socket null in OnsensorChanged()

Code:
package com.example.sensorsmart;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener{


	private static final int SERVERPORT = 8222;
	private static final String SERVER_IP = "192.168.0.101";

		private SensorManager mSensorManager;
		private Sensor mAccelerometer;
	    private   TextView tv ;
	
	    public ServerSocket serverSocket=null;
	    public Socket socket = null;
	    
		public BufferedReader in ;
		public BufferedWriter out;
		public   PrintWriter pw ;

		
		public FileWriter writer=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	    
		
		  new MyTask().execute();
		  mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		 mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		 
		  mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
	 
		
	}
	
	public void onStopClick(View view) {
	    mSensorManager.unregisterListener(this);
	}
	protected void onResume() {
	    super.onResume();
	    
	}
	
	protected void onStop(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mSensorManager.unregisterListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}


	
	private class MyTask extends AsyncTask<Void, Void,Socket>

	{

	@Override
	protected Socket doInBackground(Void... arg0) {
		// TODO Auto-generated method stub
		
		
		 
		 
		 try {
			serverSocket = new ServerSocket(8222);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		 try {
			socket=serverSocket.accept();
			
			Log.i("TcpServer", "CONNECTED");
			
			
			 
             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
             pw = new PrintWriter(socket.getOutputStream(),true);
            
           //out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        
             
             if(!in.ready())
            {
            	Log.i("TcpServer", "READER IS NOT READY");
            }
          
           final  String g;
           final String c;
           
            String b = null;
            
            
        	Log.i("TcpServer", "GOING");
           
        	g=in.readLine();
        	
			//Log.i("TcpServer", in.readLine());
        	
        	  runOnUiThread(new Runnable() {
     	         public void run() {
     	        	
     	        	 
     	            Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
     	           
     	            
     	      } 
     	     });
     	      
			
			Log.i("TcpServer", "RECEIVED");
			
		
	
      	  runOnUiThread(new Runnable() {
   	         public void run() {
   	        	
   	        	 
   	            Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
   	           
   	            
   	      } 
   	     });
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			 String  response = e.getCause().toString();
			 
			 Log.i("TCP",response);
		}
	

		 
		return socket;
	}
		
	protected void onPostExecute(Socket result) {
		socket = result;
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		pw = new PrintWriter(socket.getOutputStream(),true);


	}  
	
	
	}



@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
	// TODO Auto-generated method stub
	
}




@Override
public void onSensorChanged(SensorEvent event) {


pw.println("egaga");

}


public void CloseConn() throws IOException //not used
{
	pw.flush();
	in.close();
	socket.close();
	serverSocket.close();
	
}
	
	
	}
 

warlock9_0

Member
Apr 22, 2013
35
9
Athens
Code:
public class MainActivity extends Activity implements SensorEventListener{


	private static final int SERVERPORT = 8222;
	private static final String SERVER_IP = "192.168.0.101";

	private SensorManager mSensorManager;
	private Sensor mAccelerometer;
	private   TextView tv ;
	
	public ServerSocket serverSocket=null;
	public Socket socket = null;
	  
	public BufferedReader in ;
	public BufferedWriter out;
	public   PrintWriter pw ;

		
	public FileWriter writer=null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	    
		
		  new MyTask().execute();
		  mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		  mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		 
		  mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
	}
	
	public void onStopClick(View view) {
	    mSensorManager.unregisterListener(this);
	}
	protected void onResume() {
	    super.onResume();
	    
	}
	
	protected void onStop(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mSensorManager.unregisterListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}


	
	private class MyTask extends AsyncTask<Void, Void,AllInOne>

	{

	  @Override
	  protected AllInOne doInBackground(Void... arg0) {
		  // TODO Auto-generated method stub
		  
		  
		  
		  
		  try {
			  serverSocket = new ServerSocket(8222);
		  } catch (IOException e) {
			  // TODO Auto-generated catch block
			  e.printStackTrace();
		  }
		  
		  try {
			  socket=serverSocket.accept();
			  Log.i("TcpServer", "CONNECTED");
			  
			  
			  
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
				pw = new PrintWriter(socket.getOutputStream(),true);
			      
			      //out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			  
			      
			      if(!in.ready())
			      {
			    	  Log.i("TcpServer", "READER IS NOT READY");
			      }
			    
			      final  String g;
			      final String c;
			      
			      String b = null;
				
				
				    Log.i("TcpServer", "GOING");
			      
				    g=in.readLine();
				    
					    //Log.i("TcpServer", in.readLine());
				    
			      runOnUiThread(new Runnable() {
			      public void run() {
				      
				      
			    	  Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
				
				  
			    } 
				});
				  
					    
			    Log.i("TcpServer", "RECEIVED");
					    
				    
			    
			      runOnUiThread(new Runnable() {
				    public void run() {
					    
					    
					Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
				      
					
				  } 
				});
					    
					    
				    } catch (IOException e) {
					    // TODO Auto-generated catch block
					    e.printStackTrace();
					    
					    String  response = e.getCause().toString();
					    
					    Log.i("TCP",response);
				    }
			  
		
				  
		  return new AllInOne(socket,in,pw);
	  }
		  
	  protected void onPostExecute(AllInOne result) {
		  socket = result.so;
		  in = result.re;
		  pw = result.pr;


	  }  
	  
	  
	}



    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
	    // TODO Auto-generated method stub
	    
    }


    @Override
    public void onSensorChanged(SensorEvent event) {


    if(pw!=null) pw.println("egaga");
    else Log.e("PrintWriter", null);
    }


    public void CloseConn() throws IOException //not used
    {
	    pw.flush();
	    in.close();
	    socket.close();
	    serverSocket.close();
	    
    }
    
    
    private class AllInOne {
    	
    	public Socket so;
    	public BufferedReader re;
    	public PrintWriter pr;
    	
    	public AllInOne(Socket s, BufferedReader r, PrintWriter p ){
    		this.so = s;
    		this.re = r;
    		this.pr = p;
    	}
    	
    }

}

try this
since you are initializing in and pw inside the doinbackground, you have to pass them to the main thread
so i added another class to hold all these and i pass them on result
finally you also have to check in the onsensorchanged if the pw is null because the asynctask may have not finished yet when this is called