Categories
discuss

jQuery event when a type number field is modified by the arrows aside of the field

I have this input type=”number” field on my application:

<input type="number" id="quantidade" class="form-control">

So I have this jQuery code to execute some stuff at the event keyup:

$("#quantidade").keyup(function(event){
    //code that's working like a charm
});

That’s working well when the user enter some value on the field. But, in browsers like Chrome and Firefox, type number fields have two little arrows aside the field to increase or decrease the value:

enter image description here

Clicking on these arrows does not active the keyup event. So, how can I activate the same code when the user click on the arrows? Which kind of event I can use for that?

Answer

Try that one :

$("#quantidade").on("keyup keydown change",function(event){
    //code that's working like a charm
});
Categories
discuss

How can I decorate the REST response in Spring (Boot)?

I’ve got a Spring Boot application that returns various objects that get encoded as JSON responses and I’d like to post-process them and add information to certain super classes.

Is there a way to filter, intercept, etc. the object responses from my REST endpoints before they get encoded to JSON with Jackson.

A filter won’t work since it operates at the HttpServlet{Request,Response} level.

Answer

I guess ResponseBodyAdvice is your friend. Basically it:

Allows customizing the response after the execution of an @ResponseBody or a ResponseEntity controller method but before the body is written with an HttpMessageConverter. Implementations may be may be registered directly with RequestMappingHandlerAdapter and ExceptionHandlerExceptionResolver or more likely annotated with @ControllerAdvice in which case they will be auto-detected by both.

Here i’m intercepting all the returned Strings and make them uppercase:

@ControllerAdvice
public class MyResponseBodyAdvisor implements ResponseBodyAdvice<String> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getParameterType().equals(String.class);
    }

    @Override
    public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return body.toUpperCase();
    }
}
Categories
discuss

UNIQUE constraint failed: sqlite database : android

I am trying to insert values in table. But there is only one value inserted. I am getting an error in log cat when I am trying to insert new values.

Log cat shows :

abort at 13 in [INSERT INTO event(totalminutesfrom,dayofweek,title,location,totalminutesto,id) VALUES (?,?,?,?,?,?)]: UNIQUE constraint failed: event.id
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: Error inserting totalminutesfrom=694 dayofweek=null title=qxs location=Eded & Mariz totalminutesto=0 id=0
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: event.id (code 1555)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.EventTableHelper.addEvent(EventTableHelper.java:76)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.AddEventActivity$5.onClick(AddEventActivity.java:217)

Its showing error on these two lines while inserting row.

db.insert(TABLE, null, values);

   db.addEvent(new EventData(eventTitle,dayOfWeek,totalMinutesFrom, totalMinutesTo,location));

EventTableHelper

public class EventTableHelper extends SQLiteOpenHelper {


    private static final String TABLE = "event";
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_LOCATION = "location";
    private static final String KEY_DAY_OF_WEEK = "dayofweek";
    private static final String KEY_TOTAL_MINUTES_FROM = "totalminutesfrom";
    private static final String KEY_TOTAL_MINUTES_TO = "totalminutesto";



    public EventTableHelper(Context context) {
        super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
        //3rd argument to be passed is CursorFactory instance
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        //createTable(db);
    }

    public void createTable(SQLiteDatabase db){
        String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
                + KEY_DAY_OF_WEEK +"TEXT" + KEY_TOTAL_MINUTES_FROM +"INTEGER"
                + KEY_TOTAL_MINUTES_TO + "INTEGER" +  KEY_LOCATION + "TEXT" +  ")";

        db.execSQL(CREATE_EVENTS_TABLE);

    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
       // db.execSQL("DROP TABLE IF EXISTS " + TABLE);

      //  createTable(db);

        // Create tables again
        //onCreate(db);
    }

    // code to add the new contact
    public void addEvent(EventData event) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID, event.getId());
        values.put(KEY_TITLE,event.getTitle()); // Contact Name
        values.put(KEY_DAY_OF_WEEK,event.getDayofWeek());
        values.put(KEY_TOTAL_MINUTES_FROM,event.getFromMinutes());
        values.put(KEY_TOTAL_MINUTES_TO,event.getToMinutes());
        values.put(KEY_LOCATION,event.getLocation());
        // Inserting Row
        db.insert(TABLE, null, values);
        //2nd argument is String containing nullColumnHack
        db.close(); // Closing database connection
    }

    // code to get the single contact
   EventData getEvent(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE, new String[] { KEY_ID,
                        KEY_TITLE, KEY_DAY_OF_WEEK, KEY_TOTAL_MINUTES_FROM,KEY_TOTAL_MINUTES_TO,KEY_LOCATION }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
       EventData eventData = new EventData(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2),
               cursor.getInt(3),cursor.getInt(4),cursor.getString(5));

        return eventData;
    }



    // code to get all contacts in a list view
    public List<EventData> getAllEvents() {
        List<EventData> conList = new ArrayList<EventData>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {

                EventData event = new EventData();

                event.setId(Integer.parseInt(cursor.getString(0)));
                event.setTitle(cursor.getString(1));
                event.setDayofWeek(cursor.getString(2));
                event.setFromMinutes(cursor.getInt(3));
                event.setToMinutes(cursor.getInt(4));
                event.setLocation(cursor.getString(5));
                // Adding contact to list
                conList.add(event);
            } while (cursor.moveToNext());
        }

        // return contact list
        return conList;
    }
}

How to solve this??

Answer

Your code probably violates primary key’s uniqueness constraint on a KEY_ID field.

Two possible solutions are:

  1. Make sure that your EventData.getId() returns unique values per object. For now, I don’t see you pass any identifier to its constructor and perhaps all the events are inserted with the same id value.
  2. If you don’t care about generating ids by yourself, you can add AUTOINCREMENT setting to your KEY_ID column definition. This way KEY_ID field will be filled automatically and each row will have its own, unique value. Once there, don’t forget to remove adding KEY_ID to ContentValues by yourself.
Categories
discuss

In-app purchases made via promo codes return empty developer payload string

I have an app published to the alpha channel, with an in-app (un)managed item that costs $1.

When I purchase normally, i.e, use a credit/debit card Google returns the correct developer payload string, but if I choose to “redeem” a promo code and enter said code, Google returns an empty developer payload string, and thus authentication fails in ‘onIabPurchaseFinished()’.

I should mention that this only occurs if I choose to redeem a code from the app’s purchase flow, and everything works flawlessly if I open Play Store first, redeem the code, and then come back and open the app.

Is this a bug on Google’s part?

EDIT: The Play Store thing is expected, since it can’t know your payload and the purchase is done without having to check for it.

Answer

This issue was opened on the google’s android-play-billing samples repo.
Looks like it was ignored for a long time and was eventually closed with this comment. In short, they have following suggestions.


We reviewed our guidelines and internal APIs, and since the developerPayload is not supported across all features on In-App Billing API (including promocodes), we are removing the recommendation to use it as a security check.

As you can see in our documentation, on the page Implementing In-app Billing (https://developer.android.com/google/play/billing/billing_integrate.html) we’ve added a recommendation:

Caution: Don’t use the developerPayload field for security validation purposes. This field isn’t always available when completing tasks related to In-app Billing. For more information about security best practices, see the In-app Billing Security and Design guide.

Our recommendation is to validate on your own backend, using the Play Developer API.


Categories
discuss

GoogleApiClient is not connected despite onconnect() being called?

I want to add a geofence on the current location of the user when the user clicks on the ad geofence button.however,after using fused api client it states that its not connected yet.here is my code-

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.ArrayList;

public class MapsActivity extends FragmentActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private GoogleMap googleMap; // Might be null if Google Play services APK is not available.
    public SQLiteDatabase db;
    ArrayList<Geofence> mGeofences;
    public double latitude = 77.80;
    public double longitude = 55.76;
    Double valueindex = 0.0;
    private int request = 0;
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    /**
     * Geofence Coordinates
     */
    ArrayList<LatLng> mGeofenceCoordinates;
    /**
     * Geofence Store
     */
    private GeofenceStore mGeofenceStore;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGeofences = new ArrayList<Geofence>();
        mGeofenceCoordinates = new ArrayList<LatLng>();
        db = openOrCreateDatabase("CoordsDB", Context.MODE_PRIVATE, null);
//        db.execSQL("CREATE TABLE IF NOT EXISTS Coordinates(number DOUBLE,latitude DOUBLE,longitude DOUBLE);");
//        db.execSQL("INSERT INTO Coordinates VALUES('Fixed', 28.61,77.20)");
        setContentView(R.layout.activity_maps);
        SupportMapFragment supportMapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
        /**
         * SupportMapFragment belongs to the v4 support library, contrary to the default MagFragment that is a native component in Android.
         SupportMapFragment will support more Android versions, but it is also an additional library you have to add in your project,
         so I think it really depends on the Android versions you are targeting:
         •  On recent versions, the default components should be enough
         •  On older versions you will need to install the v4 support library and maybe others
         *
         */
        googleMap = supportMapFragment.getMap();
        Log.i("My activity", "maps=" + googleMap);
        googleMap.setMyLocationEnabled(true);
        /**
         * setMyLocationEnabled(true/false) shows the true location when the GPS is switched on from the device. It is an inbuilt feature of the googlemaps .
         */

        LocationManager locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
        // getting GPS status
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        Log.i("My activity", "gps is" + isGPSEnabled);

        // getting network status
        boolean isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        Log.i("My activity", "network is" + isNetworkEnabled);

        Criteria crta = new Criteria();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
            crta.setAccuracy(Criteria.ACCURACY_FINE);
        } else {
            crta.setAccuracy(Criteria.ACCURACY_MEDIUM);
        }
        /**
         * we have used .setAccuracy as fine for higher SDks than gingerbread .Gingerbread is used as a reference because in apks lower
         * than gingerbread there is very poor geofencing, with gingerbread google made it a lot easier for locationservices to be used for devleopers.
         * it had improved set of tools for Location Services, which included geofencing and substantially improved location discovery.
         */
        crta.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(crta, true);

        /**
         * It request Location updates after every 5 sec or if the user traveled 10m
         */
        Log.i("My activity", "manager is " + locationManager);
        Log.i("My activity", "provider is " + provider);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                return;
            }
        }
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
                    .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
            Log.i("Api is",""+mGoogleApiClient);
        }
        mLocationRequest = new LocationRequest();
        // We want a location update every 10 seconds.
        mLocationRequest.setInterval(10000);
        // We want the location to be as accurate as possible.
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

//        Location location = locationManager.getLastKnownLocation(provider);
        Location location = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        startLocationUpdates();
        Log.i("Location is", location + "");



        if (location != null) {

            onLocationChanged(location);
        }


        /**
         * the Permission is requested after every  sec or at a distance of 0 metres by the user.
         */


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 100: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Thanks for the permission", Toast.LENGTH_LONG).show();
                    // permission was granted, yay! do the
                    // calendar task you need to do.
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "You did not allow to access your current location", Toast.LENGTH_LONG).show();
                }
            }
            // other 'switch' lines to check for other
            // permissions this app might request
        }
    }


    @Override
    public void onLocationChanged(Location location) {
        CameraPosition INIT =
                new CameraPosition.Builder()
                        .target(new LatLng(location.getLatitude(), location.getLongitude()))
                        .zoom(17.5F)
                        .bearing(300F) // orientation
                        .tilt(50F) // viewing angle
                        .build();
        // use GooggleMap mMap to move camera into position
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(INIT));
    }

    @Override
    protected void onStart() {

        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {

        super.onStop();
        mGoogleApiClient.disconnect();

    }


    public void Add(View view) {
        if (request <= 3) {
            mGeofenceCoordinates.add(new LatLng(latitude, longitude));
            Log.i("The id is", "" + valueindex);
            mGeofences.add(new Geofence.Builder()
                    // The coordinates of the center of the geofence and the radius in meters.
                    .setRequestId("" + valueindex)
                    .setCircularRegion(latitude, longitude, 30)
                    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                            // Required when we use the transition type of GEOFENCE_TRANSITION_DWELL
                    .setLoiteringDelay(50000)
                    .setTransitionTypes(
                            Geofence.GEOFENCE_TRANSITION_ENTER
                                    | Geofence.GEOFENCE_TRANSITION_DWELL
                                    | Geofence.GEOFENCE_TRANSITION_EXIT).build());
            mGeofenceStore = new GeofenceStore(this, mGeofences);
            valueindex++;
            request++;

//            Cursor c = db.rawQuery("SELECT * FROM Coordinates WHERE Id='"+valueindex+"'", null);


            googleMap.addMarker(new MarkerOptions().snippet("Radius:30m").draggable(false).title(valueindex + "").position(new LatLng(latitude, longitude)));
        } else {
            Toast.makeText(this, "Maximum limit exceeded", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location mlastlocation;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
                //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                return;
            }
        }
            mlastlocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
           startLocationUpdates();
            if (mlastlocation != null) {
                Log.i("the last location:", "" + mlastlocation);
                Toast.makeText(this, "Get last location first asshole!", Toast.LENGTH_LONG).show();
            }


        }


    protected void startLocationUpdates() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                MapsActivity.this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
                //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                return;
            }
            LocationRequest mLocationRequest = new LocationRequest();

            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("connection","suspended");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.i("Connection","Failed");
    }
}

Here is my error-

java.lang.RuntimeException: Unable to start activity ComponentInfo{saksham.geofencing/saksham.geofencing.MapsActivity}: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5443)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
     Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
            at com.google.android.gms.common.api.internal.zzh.zzb(Unknown Source)
            at com.google.android.gms.common.api.internal.zzl.zzb(Unknown Source)
            at com.google.android.gms.common.api.internal.zzj.zzb(Unknown Source)
            at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source)
            at saksham.geofencing.MapsActivity.startLocationUpdates(MapsActivity.java:276)
            at saksham.geofencing.MapsActivity.onCreate(MapsActivity.java:139)
            at android.app.Activity.performCreate(Activity.java:6245)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5443)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

and my manifest file-

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="saksham.geofencing" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <!--
 The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but are recommended.
    -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <receiver android:name="com.aol.android.geofence.GeofenceReceiver"
        android:exported="false">
        <intent-filter >
            <action android:name="com.aol.android.geofence.ACTION_RECEIVE_GEOFENCE"/>
        </intent-filter>
    </receiver>

</manifest>

Please help,i am newbie to android and i have been stuck at it for many days now even after searching countless blogs

Answer

In your onCreate method, you correctly configure the Google API Client and call onConnect:

if (mGoogleApiClient == null) {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
            .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
    Log.i("Api is",""+mGoogleApiClient);
}

However, several lines below this (still within the onCreate lifecycle method), you have the following code:

Location location = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
startLocationUpdates();
Log.i("Location is", location + "");

if (location != null) {
    onLocationChanged(location);
}

My guess is that the first line of this section is causing the error – you are trying to retrieve a location but the Google API Client is still not connected at this point. Since you already have analogous code inside your onConnected callback, you should be able to just remove the second block of code I quoted above from your onCreate method to fix the issue.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..