Search code examples
androidnullpointerexceptionbroadcastreceiverandroid-service

null pointer exception in application


thanks in advance ,

i am trying to get the user current location in a service,but when i am sending the longitude and latitude through DDMS (in eclipse) then suddenly application is being forced closed the code for the service

code:

package com.android.trace;

  import java.io.BufferedReader;
  import java.io.InputStream;
 import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
 import android.os.Bundle;
import android.os.IBinder;


 import android.widget.Toast;

 public class MyService extends Service{

String tag="TestService";
double logi;
double lat;
long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Millisecon
    Location loc;
    LocationManager manager;
   @Override
   public void onCreate() {


   manager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
      manager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MINIMUM_TIME_BETWEEN_UPDATES, 
           MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
           new MyLocationListener()

   );
  Toast.makeText(MyService.this,"activity created...",Toast.LENGTH_LONG).show();
  loc=manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

  String s;
  if(loc!=null)
  {
     logi=loc.getLongitude();
     lat=loc.getLatitude();
      s="Lat:" + lat + "\nLong:" + logi;

  }
  else
  {
    s ="no location found";
  }

  Toast.makeText(this,"Your Current Position is:\n" +
          s,Toast.LENGTH_LONG).show();
  webcall(logi,lat); 

  }


     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {



   return START_STICKY;
   }
     @Override
        public void onDestroy() {
        super.onDestroy();
      Toast.makeText(MyService.this, "Service destroyed...", Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
   return null;
   }

    public void webcall(double logi,double lat)
{
    InputStream is=null;
    String result = "";
    //the year data to send
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("logitude",Double.toString(logi)));
    nameValuePairs.add(new BasicNameValuePair("latitude",Double.toString(lat)));

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/location.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    }catch(Exception e){
            Toast.makeText(MyService.this,"Error in http connection "+e.toString(),Toast.LENGTH_LONG).show();
    }
    //convert response to string
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();

             result=sb.toString();




            Toast.makeText(MyService.this,result,Toast.LENGTH_LONG).show();
    }catch(Exception e){
            Toast.makeText(MyService.this,"Error converting result "+e.toString(),Toast.LENGTH_LONG).show();
    }
}




}

 class MyLocationListener implements LocationListener
{
 public void onLocationChanged(Location location) {

     new MyService().webcall(location.getLongitude(),location.getLatitude());
 }
   public void onProviderDisabled(String s) {

 }

 public void onProviderEnabled(String s) {

 }
  public void onStatusChanged(String s, int i, Bundle b) {

 }

}

i am using the broadcast receiver to start the service at the stat up the code for broadcast receiver is

code:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBroadcastReceiver extends BroadcastReceiver {

  public void onReceive(Context context, Intent intent) {
      Intent startServiceIntent = new Intent(context, MyService.class);
      startServiceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startService(startServiceIntent);

   }
}

and the manifest is

<service android:enabled="true" android:name=".MyService">
            <intent-filter>
                <action android:name="com.android.trace.MyService"/>

            </intent-filter>
        </service>

        <receiver android:name="com.android.trace.MyBroadcastReceiver">  
            <intent-filter>  
              <action android:name="android.intent.action.BOOT_COMPLETED" />  
             </intent-filter>  
        </receiver> 
         <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
         <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

and the logcat is

    09-06 13:14:38.427: E/AndroidRuntime(255): FATAL EXCEPTION: main
     09-06 13:14:38.427: E/AndroidRuntime(255): java.lang.NullPointerException
     09-06 13:14:38.427: E/AndroidRuntime(255):     at    android.content.ContextWrapper.getResources(ContextWrapper.java:80)
     09-06 13:14:38.427: E/AndroidRuntime(255):at android.widget.Toast.<init>Toast.java:89)
     09-06 13:14:38.427:E/AndroidRuntime(255):aandroid.widget.Toast.makeText(Toast.java:231)
     09-06    13:14:38.427:E/AndroidRuntime(255):atcom.android.trace.MyService.webcall(MyService.java:128)
      09-06 13:14:38.427:E/AndroidRuntime(255):atcom.android.trace.MyLocationListener.onLocationChanged(MyService.java:141)
09-06 13:14:38.427: E/AndroidRuntime(255):  at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:191)
09-06 13:14:38.427: E/AndroidRuntime(255):  at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:124)
09-06 13:14:38.427: E/AndroidRuntime(255):  at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:140)
09-06 13:14:38.427: E/AndroidRuntime(255):  at android.os.Handler.dispatchMessage(Handler.java:99)
09-06 13:14:38.427: E/AndroidRuntime(255):  at android.os.Looper.loop(Looper.java:123)
09-06 13:14:38.427: E/AndroidRuntime(255):  at android.app.ActivityThread.main(ActivityThread.java:4627)
09-06 13:14:38.427: E/AndroidRuntime(255):  at java.lang.reflect.Method.invokeNative(Native Method)
09-06 13:14:38.427: E/AndroidRuntime(255):  at java.lang.reflect.Method.invoke(Method.java:521)
09-06 13:14:38.427: E/AndroidRuntime(255):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-06 13:14:38.427: E/AndroidRuntime(255):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-06 13:14:38.427: E/AndroidRuntime(255):  at dalvik.system.NativeStart.main(Native Method)

getting null pointer exception when the location is getting changed please help me ,i am new to android . thanks in advance.


Solution

  • You cannot instantiate your service yourself. This has to be instantiated by framework for the context to be initialized. Move MyLocationListener inside the service and

    Instead of

    new MyService().webcall 
    

    use

       MyService.this.webcall(location.getLongitude(),location.getLatitude());
    

    or just

    webcall(location.getLongitude(),location.getLatitude());