1

I'm having a NullPointerException but I'm unable to understand that what the problem is.The application is crashing when there is a call to addInDB(). Please, help me in finding out my mistake.

package com.example.streetaddress;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MyActivity extends Activity {

    Button btnGPSShowLocation;
    Button btnShowAddress;
    TextView tvAddress;
    static Context context;
    static SQLiteDatabase db;
    AppLocationService appLocationService;
    SharedPreferences prefs;
    static MyActivity obj;

protected void onResume()
    {
    super.onResume();
    if (prefs.getBoolean("firstrun", true)) 
    {       
         db=openOrCreateDatabase("PointLocationDB", Context.MODE_PRIVATE, null);
         db.execSQL("CREATE TABLE IF NOT EXISTS pointRoute(address VARCHAR);");
         db.execSQL("INSERT INTO pointRoute VALUES('MUET,Jamshoro');");
         Toast.makeText(getApplicationContext(), "records added", Toast.LENGTH_LONG).show();
         prefs.edit().putBoolean("firstrun", false).commit();
    }//end of if
    }//end of onResume()


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvAddress = (TextView) findViewById(R.id.tvAddress);
        appLocationService = new AppLocationService(MyActivity.this);
        prefs=getSharedPreferences("com.example.streetaddress", 0);
        obj=new MyActivity();
        context=getApplicationContext();
        btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
        btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Location gpsLocation = appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);
                if (gpsLocation != null) {
                    Data.plat = gpsLocation.getLatitude();
                    Data.plong = gpsLocation.getLongitude();

                    String result = "Latitude: " + gpsLocation.getLatitude() +
                            " Longitude: " + gpsLocation.getLongitude();
                    tvAddress.setText(result);
                } else {
                    showSettingsAlert();
                }
            }
        });

        btnShowAddress = (Button) findViewById(R.id.btnShowAddress);
        btnShowAddress.setOnClickListener(new View.OnClickListener() {
            @SuppressWarnings("static-access")
            @Override
            public void onClick(View arg0) {

                Cursor c=db.rawQuery("SELECT * FROM pointRoute", null);

                if(c.getCount()==0)

                        {

                        showMessage("Error", "No records found");

                        return;

                        }

                    StringBuffer buffer=new StringBuffer();
     if(c!=null && c.moveToFirst()){            


                    do{

                    buffer.append("Location: "+c.getString(0)+"\n");

                    //buffer.append("Name: "+c.getString(1)+"\n");

                    //buffer.append("Marks: "+c.getString(2)+"\n\n");

                        }while(c.moveToNext());

                showMessage("Point Location Details", buffer.toString());
     }
//                Location location = appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);
//                  if (location != null) {
                  //  Data.plat = location.getLatitude();
                   // Data.plong = location.getLongitude();
                    LocationAddress locationAddress = new LocationAddress();
                    locationAddress.getAddressFromLocation(Data.plat, Data.plong,
                            getApplicationContext(), new GeocoderHandler());
                //} else {
                  //  showSettingsAlert();



            }   });

    }
    public void showMessage(String title,String message)

    {

    Builder builder=new Builder(this);

    builder.setCancelable(true);

    builder.setTitle(title);

    builder.setMessage(message);

    builder.show();

    }

@SuppressWarnings("static-access")
public static void addLocationInDB(double lat,double longi){
    LocationAddress locationAddress = new LocationAddress();
    locationAddress.getAddressFromLocation(lat, longi,
            context, obj.new GeocoderHandler());

    Cursor c=db.rawQuery("SELECT * FROM pointRoute", null);
    if(c.moveToFirst()&& c!=null){    
do{
    if(!((Data.locAddress.equals(" ")) && (Data.locAddress.equals(c.getString(0))))){
db.execSQL("INSERT INTO pointRoute VALUES('"+Data.locAddress+"');");
    }
}while(c.moveToNext());
}
}



    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                MyActivity.this);
        alertDialog.setTitle("SETTINGS");
        alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        MyActivity.this.startActivity(intent);
                    }
                });
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        alertDialog.show();
    }

    @SuppressLint("HandlerLeak")
    private class GeocoderHandler extends Handler {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case 1:
                    Bundle bundle = message.getData();
                    Data.locAddress = bundle.getString("address");
                    break;
                default:
                     Data.locAddress = null;
            }
            tvAddress.setText( Data.locAddress);
        }
    }
}

AppLocationService.java

package com.example.streetaddress;

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;

public class AppLocationService extends Service implements LocationListener {

    protected LocationManager locationManager;
    Location location;

    private static final long MIN_DISTANCE_FOR_UPDATE = 10;
    private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

    public AppLocationService(Context context) {
        locationManager = (LocationManager) context
                .getSystemService(LOCATION_SERVICE);
    }

    public Location getLocation(String provider) {
        if (locationManager.isProviderEnabled(provider)) {
            locationManager.requestLocationUpdates(provider,
                    MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
            if (locationManager != null) {
                location = locationManager.getLastKnownLocation(provider);
                return location;
            }
        }
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
    Data.plat=location.getLatitude();
    Data.plong=location.getLongitude();
    MyActivity.addLocationInDB(Data.plat,Data.plong);
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

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

}

LocationAddress.java

package com.example.streetaddress;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class LocationAddress {
    private static final String TAG = "LocationAddress";

    public static void getAddressFromLocation(final double latitude, final double longitude,
                                              final Context context, final Handler handler) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String result = null;
                try {
                    List<Address> addressList = geocoder.getFromLocation(
                            latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i)).append("\n");
                        }
                        sb.append(address.getLocality()).append("\n");
                        sb.append(address.getPostalCode()).append("\n");
                        sb.append(address.getCountryName());
                        result = sb.toString();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable connect to Geocoder", e);
                } finally {
                    Message message = Message.obtain();
                    message.setTarget(handler);
                    if (result != null) {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = "Latitude: " + latitude + " Longitude: " + longitude +
                                "\n\nAddress:\n" + result;
                        bundle.putString("address", result);
                        message.setData(bundle);
                    } else {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = "Latitude: " + latitude + " Longitude: " + longitude +
                                "\n Unable to get address for this lat-long.";
                        bundle.putString("address", result);
                        message.setData(bundle);
                    }
                    message.sendToTarget();
                }
            }
        };
        thread.start();
    }
}

logcat when i click btnshowAddress:

09-13 16:41:54.859: E/AndroidRuntime(4557): FATAL EXCEPTION: main
09-13 16:41:54.859: E/AndroidRuntime(4557): java.lang.NullPointerException
09-13 16:41:54.859: E/AndroidRuntime(4557):     at com.example.streetaddress.MyActivity$2.onClick(MyActivity.java:102)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at android.view.View.performClick(View.java:3571)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at android.view.View$PerformClick.run(View.java:14247)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at android.os.Handler.handleCallback(Handler.java:605)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at android.os.Looper.loop(Looper.java:137)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at android.app.ActivityThread.main(ActivityThread.java:4517)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at java.lang.reflect.Method.invokeNative(Native Method)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at java.lang.reflect.Method.invoke(Method.java:511)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
09-13 16:41:54.859: E/AndroidRuntime(4557):     at dalvik.system.NativeStart.main(Native Method)

logcat when i click btnGPSshowAddress:

09-13 16:44:48.409: E/AndroidRuntime(4668): FATAL EXCEPTION: main
09-13 16:44:48.409: E/AndroidRuntime(4668): java.lang.NullPointerException
09-13 16:44:48.409: E/AndroidRuntime(4668):     at com.example.streetaddress.MyActivity.addLocationInDB(MyActivity.java:167)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at com.example.streetaddress.AppLocationService.onLocationChanged(AppLocationService.java:41)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:260)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:193)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:209)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at android.os.Looper.loop(Looper.java:137)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at android.app.ActivityThread.main(ActivityThread.java:4517)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at java.lang.reflect.Method.invokeNative(Native Method)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at java.lang.reflect.Method.invoke(Method.java:511)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
09-13 16:44:48.409: E/AndroidRuntime(4668):     at dalvik.system.NativeStart.main(Native Method)
09-13 16:44:53.449: E/LocationAddress(4668): Unable connect to Geocoder
09-13 16:44:53.449: E/LocationAddress(4668): java.io.IOException: Unable to parse response from server
09-13 16:44:53.449: E/LocationAddress(4668):    at android.location.Geocoder.getFromLocation(Geocoder.java:136)
09-13 16:44:53.449: E/LocationAddress(4668):    at com.example.streetaddress.LocationAddress$1.run(LocationAddress.java:26)

1 Answers1

0
  1. Please, check the following line:

    Cursor c=db.rawQuery("SELECT * FROM pointRoute", null);
    

    in onCreate() where the accessing the variable db doesn't make any sense.

    However, you are initializing the same db in onResume():

    db=openOrCreateDatabase("PointLocationDB", Context.MODE_PRIVATE, null);
    
  2. Also the same holds here too:

    public static void addLocationInDB(double lat,double longi){
        ...
        Cursor c=db.rawQuery("SELECT * FROM pointRoute", null);
    
TryinHard
  • 4,078
  • 3
  • 28
  • 54