0

I have a problem with permissions on my application, I actually get a first error "java.lang.ArrayIndexOutOfBoundsException: length = 0; index = 0" and then a second due to the permissions, but the application works although when it is a lower version 6 due to its:

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

This can perhaps come to onRequestPermissionsResult? The application asks me permissions only after the application of GPS to happen, application crash so because the code that requires permission is read before the permissions ask .. can we set a priority? So I give you my code:

public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

private static final int GPS = 1002;
GoogleMap map;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    final Context myContext2 = this.getApplicationContext();


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
            }

            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    GPS);

        }
    }

    LocationManager locationManager;
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

        Intent localIntent = new Intent(this, AlertGPS.class);
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(localIntent);


    } else {

    map.setMyLocationEnabled(true);
    map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    Criteria criteria = new Criteria();

    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)) ;

    if (location != null) {
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(location.getLatitude(), location.getLongitude()), 13));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                .zoom(17)                   // Sets the zoom
                .bearing(90)                // Sets the orientation of the camera to east
                .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    } }

    FloatingActionButton sync = (FloatingActionButton) findViewById(R.id.sync);
    sync.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(final View view) {

            SharedPreferences sharedPreferences = Main2Activity.this.getSharedPreferences("appSharedPreferences", Context.MODE_PRIVATE);
            String lockphone = sharedPreferences.getString("lockphone", null);

            if(lockphone == null){
                Snackbar.make(view, "Merci d'établir une connexion GSM avec Locate iT dans les paramètres.", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

            }
            else {
                SmsManager smsManager = SmsManager.getDefault();
                String receiver = lockphone;
                String body = "LR";
                String SENT = "SMS_SENT";
                String DELIVERED = "SMS_DELIVERED";

                PendingIntent sentIntent = PendingIntent.getBroadcast(myContext2, 0, new Intent(SENT), 0);
                PendingIntent deliveredIntent = PendingIntent.getBroadcast(myContext2, 0, new Intent(DELIVERED), 0);
                smsManager.sendTextMessage(receiver, null, body, sentIntent, deliveredIntent);


                myContext2.registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                Snackbar.make(view, "La synchronisation à démarrée.", Snackbar.LENGTH_LONG)
                                        .setAction("Action", null).show();
                                break;
                            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                                Snackbar.make(view, "Erreur dans le numéro de télephone, merci d'effacer les données de l'application et rétablir une connection GSM.", Snackbar.LENGTH_LONG)
                                        .setAction("Action", null).show();
                                break;
                            case SmsManager.RESULT_ERROR_NO_SERVICE:
                                Snackbar.make(view, "Aucun réseau disponible", Snackbar.LENGTH_LONG)
                                        .setAction("Action", null).show();
                                break;
                            case SmsManager.RESULT_ERROR_RADIO_OFF:
                                Snackbar.make(view, "Réseau désactivé sur votre appareil.", Snackbar.LENGTH_LONG)
                                        .setAction("Action", null).show();
                                break;
                        }
                    }
                }, new IntentFilter(SENT));

                myContext2.registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                Snackbar.make(view, "Réponse de Locate iT en attente.", Snackbar.LENGTH_LONG)
                                        .setAction("Action", null).show();
                                break;
                            case Activity.RESULT_CANCELED:
                                Snackbar.make(view, "Opération annulé par un intent.", Snackbar.LENGTH_LONG)
                                        .setAction("Action", null).show();
                                break;
                        }
                    }
                }, new IntentFilter(DELIVERED));


            }
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


}

@Override
public void onBackPressed() {

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.vue, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.normal:
            GoogleMap map2 = ((MapFragment) getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            map2.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            return true;
        case R.id.satellite:
            GoogleMap map = ((MapFragment) getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            return true;
        case R.id.terrain:
            GoogleMap map3 = ((MapFragment) getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            map3.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            return true;
        case R.id.hybride:
            GoogleMap map4 = ((MapFragment) getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            map4.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            return true;
        case R.id.vide:
            GoogleMap map5 = ((MapFragment) getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            map5.setMapType(GoogleMap.MAP_TYPE_NONE);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }

}

@Override
public boolean onNavigationItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.nav_manage) {
        Intent intent = new Intent(Main2Activity.this, Setting.class);
        startActivity(intent);

    } else if (id == R.id.nav_Changelog) {
        Intent intent = new Intent(Main2Activity.this, Changelog.class);
        startActivity(intent);

    } else if (id == R.id.nav_lequipe) {

        Intent intent = new Intent(Main2Activity.this, lequipe.class);
        startActivity(intent);

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                       int[] grantResults) {

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                }

                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        GPS);
            }

            }
        else {
            Toast.makeText(this, "Permission refusée, la localisation sera désactivée. Certaines fonctions seront inopérantes.", Toast.LENGTH_SHORT)
                    .show();
        }


}

@Override
public void onResume() {
    super.onResume();


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
            }

            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    GPS);

        }
    }

    map.setMyLocationEnabled(true);
    map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    if (location != null) {
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(location.getLatitude(), location.getLongitude()), 13));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                .zoom(17)                   // Sets the zoom
                .bearing(90)                // Sets the orientation of the camera to east
                .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }


}

 }
Antholife
  • 21
  • 4
  • Like many things in Android, `requestPermissions()` is asynchronous. You are assuming that it is synchronous and that you are guaranteed to have the permission when it returns. Neither assumption is true. If you call `requestPermissions()`, then also delay all your `LocationManager` work until inside `onRequestPermissionsResult()`, and then only if you actually got the permission. – CommonsWare Apr 16 '16 at 12:50
  • Thank you ! But I am beginner, I do not completely understand do the asynchronous and synchronous terms ...; I ask you some explanation more detailed and if possible, thank you :) – Antholife Apr 16 '16 at 13:00
  • Possible duplicate of [Can't turn on location on android api23?](http://stackoverflow.com/questions/42351834/cant-turn-on-location-on-android-api23) – Tomás Rodrigues Feb 21 '17 at 11:25

0 Answers0