Хобрук: Ваш путь к мастерству в программировании

java.lang.IllegalArgumentException: недопустимый провайдер: ноль

У меня проблема с провайдером, по-видимому, мое приложение вылетает при запуске, хотя я включил разрешения COARSE и FINE для определения местоположения в своем манифесте (самые последние ответы, найденные в Интернете). У меня также добавлено разрешение INTERNET. Во время тестирования на моем телефоне у меня включены WIFI и GPS. Я действительно не понимаю, в чем проблема, даже я перезагрузил свой телефон, чтобы убедиться, и у меня такая же проблема. Он возвращает недопустимое исключение аргумента null в строке провайдера.

    public class MainActivity extends FragmentActivity implements LocationListener{

GoogleMap mGoogleMap;
Spinner mSprPlaceType;

String[] mPlaceType=null;
String[] mPlaceTypeName=null;

double mLatitude=0;
double mLongitude=0;

HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

// Array of place types
    mPlaceType = getResources().getStringArray(R.array.place_type);

// Array of place type names
    mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

// Creating an array adapter with an array of Place types
// to populate the spinner
    ArrayAdapter adapter = new ArrayAdapter(this, 
    android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

// Getting reference to the Spinner
    mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

// Setting adapter on Spinner to set place types
    mSprPlaceType.setAdapter(adapter);

    Button btnFind;

 // Getting reference to Find Button
    btnFind = ( Button ) findViewById(R.id.btn_find);

 // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    }else { // Google Play Services are available



// Getting reference to the SupportMapFragment
        SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

// Getting Google Map
        mGoogleMap = fragment.getMap();

// Enabling MyLocation in Google Map
        mGoogleMap.setMyLocationEnabled(true);

 // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);



// Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

// Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

// Getting Current Location From GPS
 /******* IllegalArgumentException HERE *******/
        Location location = locationManager.getLastKnownLocation(provider);

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

        locationManager.requestLocationUpdates(provider, 20000, 0, this);

        mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker arg0) {
                Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
                String reference = mMarkerPlaceLink.get(arg0.getId());
                intent.putExtra("reference", reference);

 // Starting the Place Details Activity
                startActivity(intent);
            }
        });

 // Setting click event lister for the find button
        btnFind.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                String type = mPlaceType[selectedPosition];

                StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                sb.append("location="+mLatitude+","+mLongitude);
                sb.append("&radius=5000");
                sb.append("&types="+type);
                sb.append("&sensor=true");
                sb.append("&key=API_KEY");

 // Creating a new non-ui thread task to download Google place json data
                PlacesTask placesTask = new PlacesTask();

 // Invokes the "doInBackground()" method of the class PlaceTask
                placesTask.execute(sb.toString());

            }
        });

    }

}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);

 // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

 // Connecting to url
        urlConnection.connect();

 // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while( ( line = br.readLine()) != null){
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }

    return data;
}

/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{

    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result){
        ParserTask parserTask = new ParserTask();

 // Start parsing the Google places in JSON format
 // Invokes the "doInBackground()" method of the class ParseTask
        parserTask.execute(result);
    }

}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected List<HashMap<String,String>> doInBackground(String... jsonData) {

        List<HashMap<String, String>> places = null;
        PlaceJSONParser placeJsonParser = new PlaceJSONParser();

        try{
            jObject = new JSONObject(jsonData[0]);

 /** Getting the parsed data as a List construct */
            places = placeJsonParser.parse(jObject);

        }catch(Exception e){
            Log.d("Exception",e.toString());
        }
        return places;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(List<HashMap<String,String>> list){

 // Clears all the existing markers
        mGoogleMap.clear();

        for(int i=0;i <list.size();i++){

 // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

 // Getting a place from the places list
            HashMap<String, String> hmPlace = list.get(i);

 // Getting latitude of the place
            double lat = Double.parseDouble(hmPlace.get("lat"));

 // Getting longitude of the place
            double lng = Double.parseDouble(hmPlace.get("lng"));

 // Getting name
            String name = hmPlace.get("place_name");

 // Getting vicinity
            String vicinity = hmPlace.get("vicinity");

            LatLng latLng = new LatLng(lat, lng);

 // Setting the position for the marker
            markerOptions.position(latLng);

 // Setting the title for the marker.
 //This will be displayed on taping the marker
            markerOptions.title(name + " : " + vicinity);

 // Placing a marker on the touched position
            Marker m = mGoogleMap.addMarker(markerOptions);

 // Linking Marker id and place reference
            mMarkerPlaceLink.put(m.getId(), hmPlace.get("reference"));

        }

    }

}

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

@Override
public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
    LatLng latLng = new LatLng(mLatitude, mLongitude);

    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

}


@Override
public void onProviderDisabled(String provider) {
 // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
 // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
 // TODO Auto-generated method stub
}
 }

А вот и логкэт:

    10-27 13:45:52.615  13986-13986/com.pfe.neighborhoodserviceslbs
    E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.pfe.neighborhoodserviceslbs, PID: 13986
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pfe.neighborhoodserviceslbs/com.pfe.neighborhoodserviceslbs.MainActivity}: java.lang.IllegalArgumentException: invalid provider: null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.IllegalArgumentException: invalid provider: null
        at android.location.LocationManager.checkProvider(LocationManager.java:1704)
        at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1194)
        at com.pfe.neighborhoodserviceslbs.MainActivity.onCreate(MainActivity.java:129)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

 


  • Вы получаете эту ошибку, скорее всего, из-за недоступности провайдеров GPS. Попросите человека проверить настройки, если в настройках местоположения включен поставщик услуг GPS или поставщик сети. 27.10.2015
  • Он включен на устройстве 27.10.2015

Ответы:


1

Я нашел решение проблемы! Проблема связана с API 23, после некоторых исследований я решил перейти на API 21, и он работал нормально.

Итак, я изменил свой build.gradle, как показано ниже:

compileSdkВерсия 21

buildToolsVersion "21.1.2"

27.10.2015
Новые материалы

Основы принципов S.O.L.I.D, Javascript, Git и NoSQL
каковы принципы S.O.L.I.D? Принципы SOLID призваны помочь разработчикам создавать надежные, удобные в сопровождении приложения. мы видим пять ключевых принципов. Принципы SOLID были разработаны..

Как настроить Selenium в проекте Angular
Угловой | Селен Как настроить Selenium в проекте Angular Держите свое приложение Angular и тесты Selenium в одной рабочей области и запускайте их с помощью Mocha. В этой статье мы..

Аргументы прогрессивного улучшения почти всегда упускают суть
В наши дни в кругах веб-разработчиков много болтают о Progressive Enhancement — PE, но на самом деле почти все аргументы с обеих сторон упускают самую фундаментальную причину, по которой PE..

Введение в Джанго Фреймворк
Схема «работать умно, а не усердно» В этой и последующих статьях я познакомлю вас с тем, что такое фреймворк Django и как создать свое первое приложение с помощью простых и понятных шагов, а..

Настольный ПК как «одно кольцо, чтобы править всеми» домашних компьютеров
Вид после 9 месяцев использования С настольных компьютеров все началось, но в какой-то момент они стали «серверами», и мы все перешли на ноутбуки. В прошлом году я столкнулся с идеей настольных..

Расширенные методы безопасности для VueJS: реализация аутентификации без пароля
Руководство, которое поможет вам создавать безопасные приложения в долгосрочной перспективе Безопасность приложений часто упускается из виду в процессе разработки, потому что основная..

стройный-i18следующий
Представляем стройную оболочку для i18next. Эта библиотека, основанная на i18next, заключает экземпляр i18next в хранилище svelte и отслеживает события i18next, такие как languageChanged,..