0

I am creating a GPS tracking application, I am in beginning stage, I have traced the latitude and Longitude using LocationManager, now the next thing I want to do is to store all the data in database, I have created Adapter class and am calling it from MainActivity but am getting NullPointerException while binding the Context and Opening the database, please look at my Logcat details and please suggest me a solution.

I am getting the error message near

dbAdapter = new LocationDbAdapter(this);
dbAdapter.open(); 

Error Log :

android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:234)
android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:149)
om.example.androidtrackingapplication.LocationDbAdapter.open(LocationDbAdapter.java:78)

I have attached Complete Logcat file below please check and let me know where I am going Wrong.

I am sending the Location to the Adapter Class where it will fetch the values and store in the table .

I am calling database instance when I get the locationupdate, When I click on Locate Button which will calls LocationManager to get Location Update (This the point where my application crashes).

LocationDbAdapter.java

            import android.content.ContentValues;
            import android.content.Context;
            import android.database.Cursor;
            import android.database.SQLException;
            import android.database.sqlite.SQLiteDatabase;
            import android.database.sqlite.SQLiteOpenHelper;
            import android.location.Location;
            import android.util.Log;

            public class LocationDbAdapter {

                public static final String KEY_NAME = "name";
                public static final String KEY_LATITUDE = "latitude";
                public static final String KEY_LONGITUDE = "longitude";
                public static final String KEY_ACCURACY = "accuracy";
                public static final String KEY_TIME = "time";
                public static final String KEY_ROWID = "_id";

                private static final String TAG = "LocationDbAdapter";
                private DatabaseHelper mDbHelper;
                private SQLiteDatabase mDb;

                private static final String DATABASE_CREATE =
                    "create table locations (_id integer primary key autoincrement, "
                    + "name text not null, latitude real not null, longitude real not null, accuracy integer not null, time integer not null);";

                private static final String DATABASE_NAME = "data";
                private static final String DATABASE_TABLE = "locations";
                private static final int DATABASE_VERSION = 4;

                private final Context mCtx;

                private static class DatabaseHelper extends SQLiteOpenHelper {

                    DatabaseHelper(Context context) {
                        super(context, DATABASE_NAME, null, DATABASE_VERSION);
                    }

                    @Override
                    public void onCreate(SQLiteDatabase db) {

                        db.execSQL(DATABASE_CREATE);
                    }

                    @Override
                    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                        Log.i(TAG, "Upgrading database from version " + oldVersion + " to "
                                + newVersion + ", which will destroy all old data");
                        db.execSQL("DROP TABLE IF EXISTS locations");
                        onCreate(db);
                    }
                }

                /**
                 * Constructor - takes the context to allow the database to be
                 * opened/created
                 * 
                 * @param ctx the Context within which to work
                 */
                public LocationDbAdapter(Context ctx) {
                    this.mCtx = ctx;

                }

                /**
                 * Open the notes database. If it cannot be opened, try to create a new
                 * instance of the database. If it cannot be created, throw an exception to
                 * signal the failure
                 * 
                 * @return this (self reference, allowing this to be chained in an
                 *         initialization call)
                 * @throws SQLException if the database could be neither opened or created
                 */
                public LocationDbAdapter open() throws SQLException {
                    mDbHelper = new DatabaseHelper(mCtx);
                    mDb = mDbHelper.getWritableDatabase();
                    return this;
                }

                public void close() {
                    mDbHelper.close();
                }


                /**
                 * Add new location. If the location is
                 * successfully created return the new rowId, otherwise return
                 * a -1 to indicate failure.
                 * 
                 * @param location
                 * @return rowId or -1 if failed
                 */
                public long addLocation(Location location) {
                    Log.i(TAG, "Writing new location:"+location.toString());
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(KEY_NAME, location.getProvider());
                    contentValues.put(KEY_LATITUDE, location.getLatitude());
                    contentValues.put(KEY_LONGITUDE, location.getLongitude());
                    contentValues.put(KEY_ACCURACY, location.getAccuracy());
                    contentValues.put(KEY_TIME, location.getTime());

                    return mDb.insert(DATABASE_TABLE, null, contentValues);
                }

                public int clearDatabase() {
                    Log.i(TAG, "clearDatabase()");
                    return mDb.delete(DATABASE_TABLE, null, null);
                }

                public Cursor fetchAllLocations() {

                    return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_LATITUDE, KEY_LONGITUDE, KEY_ACCURACY,
                            KEY_TIME}, null, null, null, null, null);
                }
            }

MainActivity.java

        package com.example.androidtrackingapplication;

        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.util.Timer;
        import java.util.TimerTask;

        import org.apache.http.HttpResponse;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.impl.client.DefaultHttpClient;



        import android.app.Activity;
        import android.app.Service;
        import android.content.Context;
        import android.content.Intent;
        import android.content.IntentFilter;
        import android.location.GpsStatus;
        import android.location.Location;
        import android.location.LocationListener;
        import android.location.LocationManager;
        import android.location.LocationProvider;
        import android.os.BatteryManager;
        import android.os.Bundle;
        import android.os.CountDownTimer;
        import android.os.IBinder;
        import android.util.Log;
        import android.view.View;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.Toast;


        public class MainActivity extends Activity

        {
            LocationManager mlocManager ;
             LocationListener mlocListener ;
              Location loc;
            double lat;
            double  longitude;
             EditText Lat;
             EditText Long,battery,hitTime,intervalTime;
             int level = -1;
             static int i;
            Button Send,Reset,Locate,Close;     

            private LocationDbAdapter dbAdapter;
            Timer t;
            protected CountDownTimer waitTimer;

        /** Called when the activity is first created. */

        @Override

        public void onCreate(Bundle savedInstanceState)

        {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Lat= (EditText) findViewById(R.id.editText1);
        Long=(EditText) findViewById(R.id.editText2);


        //hitTime= (EditText) findViewById(R.id.editText3);
        //intervalTime=(EditText) findViewById(R.id.editText4);

        Locate=(Button) findViewById(R.id.button1);
        Send= (Button) findViewById(R.id.button2);

        Close=(Button) findViewById(R.id.button3);




        Locate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

            //    String hit=hitTime.getText().toString();
              //  int hit1= Integer.parseInt(hit);
               // System.out.println("Hit"+hit1);


                 Send.setEnabled(false);
                  Lat.setText(" ");
                   Long.setText(" ");

           /*  Enable the Gps    */

                  Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
               intent.putExtra("enabled", true);
               sendBroadcast(intent);

                     waitTimer = new CountDownTimer(60000,1000) {

                           public void onTick(long millisUntilFinished) {
                              i = i+1;
                                System.out.println("IN:"+i);


                                  mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
                                  mlocListener = new MyLocationListener();
                             loc = mlocManager.getLastKnownLocation( LocationManager.GPS_PROVIDER);

                            //      mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,300000, 0, mlocListener);
                            //mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,mlocListener, null);

                           mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,mlocListener, null);
                           }

                           public void onFinish() {
                           System.out.println("Location not found");
                         Toast.makeText(getApplicationContext(), "Location Not Found ", Toast.LENGTH_LONG).show();

                         if(mlocManager!=null)
                         { 

                         }
                            Lat.setText(" ");
                       Long.setText(" ");


                      if(loc!=null)
                      {
                          Lat.setText(String.valueOf(loc.getLatitude()));
                          Long.setText(String.valueOf(loc.getLongitude()));
                      }
                      Toast.makeText(getApplicationContext(), "Last Location ",Toast.LENGTH_LONG).show();



                    Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
                       intent.putExtra("enabled", false);
                       sendBroadcast(intent);

                           }
                         }.start();

            }
        });






        Send.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {





            // String lat1="15.012345";
            // String longitude1="75.012345";
           HttpClient httpClient = new DefaultHttpClient();

            String postURL = "";

            postURL = "http://bb.trackfleet.biz/android_gps/lat_long.php?lat="+lat+"&long="+longitude;


            HttpPost httpPost = new HttpPost(postURL);

            HttpResponse httpResponse = null;

            try
            {
                Toast.makeText(getApplicationContext(),"send", Toast.LENGTH_SHORT).show();
                httpResponse = httpClient.execute(httpPost); 

                String str = inputStreamToString(httpResponse.getEntity().getContent()).toString();

                Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
            }
            catch(Exception ex)
            {
                Toast.makeText(getApplicationContext(),"error", Toast.LENGTH_SHORT).show(); 

            }

            }
        });


        Close.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


                if(mlocManager!=null)
                {
                    mlocManager.removeUpdates(mlocListener);
                   mlocManager=null;
                }

                Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
                   intent.putExtra("enabled", false);
                   sendBroadcast(intent);

        finish();   



            }
        });




        }






        private StringBuilder inputStreamToString(InputStream is) {
            String line = "";
            StringBuilder total = new StringBuilder();
            // Wrap a BufferedReader around the InputStream
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            // Read response until the end
            try {
                while ((line = rd.readLine()) != null) { 
                    total.append(line); 
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            // Return full string
            return total;
        }

MyLocationListener Service

        public class MyLocationListener extends Service implements LocationListener

        {

            @Override
            public void onCreate() {

                dbAdapter = new LocationDbAdapter(this);
                dbAdapter.open();
            }




        @Override

        public void onLocationChanged(Location loc)

        {

        if(loc!=null)
        {
            dbAdapter = new LocationDbAdapter(this);
            dbAdapter.open();
            long id=dbAdapter.addLocation(loc);
            Toast.makeText(getApplicationContext(), "Added Data Sucessfully " +id ,Toast.LENGTH_SHORT).show();
        }   
        lat=loc.getLatitude();

        longitude=loc.getLongitude();

           waitTimer.cancel();
         String Text = "My current location is: " +

        "Latitud = " + loc.getLatitude() +

        "Longitud = " + loc.getLongitude();


        Lat.setText(String.valueOf(lat));
        Long.setText(String.valueOf(longitude));


        if((Lat.getText()!=null) && (Long.getText()!=null))
        {
              Send.setEnabled(true);


              Send.performClick();


        }



        }


        @Override

        public void onProviderDisabled(String provider)

        {

        Toast.makeText( getApplicationContext(),"Gps Disabled Pls Enable It",Toast.LENGTH_SHORT ).show();
        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

        }


        @Override

        public void onProviderEnabled(String provider)

        {

        Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();

        }


        @Override

        public void onStatusChanged(String provider, int status, Bundle extras)

        {

        }

        @Override
        public void onDestroy()
        {

            super.onDestroy();
            dbAdapter.close();
            mlocManager.removeUpdates(this);
        }
        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
        }
        }
        }
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
krish
  • 641
  • 3
  • 9
  • 26

1 Answers1

0

If you ask me your schema is not correct for sqlite, if 'autoincrement' by sqlite is the functionality you need you have to use:

id INTEGER PRIMARY KEY

The autoincrement that you have there shouldn't be there.

Or the autoincrementation doesn't work. See create docs

By the way, you could speed up your application a lot if you use INTEGERS to save the coordinates, instead of float/double etc. Check out this answer of mine explaining how you can easily use integers. It's very useful to be able to use integers. (index , memcache keys etc )

update: Tested on sqlite2/3. Works on sqlite3 but not on sqlite2:

SQL error: near "autoincrement": syntax error

So if the target is sqlite3 , your good to go.

Community
  • 1
  • 1
Glenn Plas
  • 1,608
  • 15
  • 17
  • My id is primary key itself , @prosper I have did according to you , I am not getting this error ndroid.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:149) but – krish Dec 25 '12 at 10:40
  • still i have some more error pls check out at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:131) 12-25 15:59:21.893: E/AndroidRuntime(8264): at com.example.androidtrackingapplication.MainActivity$MyLocationListener.onLocationChanged(MainActivity.java:266) – krish Dec 25 '12 at 10:41
  • I'm just saying that keyword autoincrement doesn't belong there, and has to fail on sqlite, which I tested and it seems to work fine for sqlite3 but not for sqlite2 with "SQL error: near "autoincrement": syntax error". – Glenn Plas Dec 25 '12 at 10:46
  • Thank you But ur solution is diverting from my problem ,My schema is working fine now i can see the result and it is working on sqlite .. – krish Dec 25 '12 at 10:55
  • So, what did you fix then ? – Glenn Plas Dec 25 '12 at 13:40
  • Great. tx for sharing, you should answer your own question now and approve it for neatness sake. – Glenn Plas Dec 27 '12 at 11:05