How to Root Android Wear 5.0.1 Lollipop Devices – XDA TV

The Lollipop update for Android Wear devices has hit the market and people are … more

Android 5.0.2 and New Factory Images For Nexus 7 (Wi-Fi) Available

Android 5.0 is has been publicly available since early November, and the … more

Github Tutorial App Shows You How to Use… Github

Github can get pretty complicated and using it can become quite daunting, especially … more

Google Glass-like Clip-On For Regular Glasses Developed by Sony

For the price of $2,000, a pair of glasses that can run apps, take pictures, … more

Welcome to XDA

Search to go directly to your device's forum

Register an account

Unlock full posting privileges

Ask a question

No registration required
Post Reply

[Q] Socket code throws NullPointerException in OnsensorChanged

OP flavglen

7th February 2014, 06:08 AM   |  #1  
OP Junior Member
Thanks Meter: 0
 
7 posts
Join Date:Joined: Feb 2014
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)
7th February 2014, 12:22 PM   |  #2  
warlock9_0's Avatar
Member
Flag Athens
Thanks Meter: 9
 
32 posts
Join Date:Joined: Apr 2013
More
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
7th February 2014, 03:33 PM   |  #3  
OP Junior Member
Thanks Meter: 0
 
7 posts
Join Date:Joined: Feb 2014
Unhappy Can u gv example ?
Quote:
Originally Posted by warlock9_0

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

frend can u give me an example ?
7th February 2014, 04:45 PM   |  #4  
warlock9_0's Avatar
Member
Flag Athens
Thanks Meter: 9
 
32 posts
Join Date:Joined: Apr 2013
More
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
8th February 2014, 02:08 PM   |  #5  
OP Junior Member
Thanks Meter: 0
 
7 posts
Join Date:Joined: Feb 2014
Unhappy 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 by flavglen; 8th February 2014 at 02:50 PM.
8th February 2014, 09:08 PM   |  #6  
warlock9_0's Avatar
Member
Flag Athens
Thanks Meter: 9
 
32 posts
Join Date:Joined: Apr 2013
More
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 by warlock9_0; 8th February 2014 at 09:16 PM. Reason: copy/paste mistake
9th February 2014, 04:44 AM   |  #7  
OP Junior Member
Thanks Meter: 0
 
7 posts
Join Date:Joined: Feb 2014
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();
	
}
	
	
	}
9th February 2014, 01:55 PM   |  #8  
warlock9_0's Avatar
Member
Flag Athens
Thanks Meter: 9
 
32 posts
Join Date:Joined: Apr 2013
More
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
9th February 2014, 03:35 PM   |  #9  
OP Junior Member
Thanks Meter: 0
 
7 posts
Join Date:Joined: Feb 2014
null
async task not completed because of socket not closed?
9th February 2014, 05:02 PM   |  #10  
OP Junior Member
Thanks Meter: 0
 
7 posts
Join Date:Joined: Feb 2014
Thumbs up Thank u
bro..some how i managed to get it work..thanks a lot for ur time..and nice to meet u..

Post Reply Subscribe to Thread
Previous Thread Next Thread
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes