2017-09-19 3 views
-1

Je travaille actuellement sur une application de studio Android. J'ai ajouté un bouton qui ouvre une boîte de dialogue dans laquelle j'ai besoin d'afficher la météo de la ville des utilisateurs. En ce moment j'ai beaucoup de mal à faire ça. Par exemple, une erreur comme celle-ci est apparue et je sais que cette question a déjà été répondue mais j'ai encore beaucoup de problèmes avec elle.Tentative d'invocation de la méthode virtuelle 'int java.lang.String.length()' sur une référence d'objet null. Comment puis-je résoudre ça?

java.lang.NullPointerException: Tentative d'invoquer la méthode virtuelle « int java.lang.String.length() » sur une référence d'objet nul

En dehors de cela, dois-je faire autre chose pour le rendre travail?

C'est le code que j'ai:

MapsActivity public class étend FragmentActivity implémente OnMapReadyCallback, LocationListener {

private GoogleMap mMap; 
LocationManager locationManager; 
String provider; 
LatLng myPosition; 

TextView climaText; 




@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 

    climaText = (TextView) findViewById(R.id.climaText); 

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    provider = locationManager.getBestProvider(new Criteria(), false); 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     return; 
    } 
    locationManager.requestLocationUpdates(provider, 400, 1, this); 


    /* locationRequest = new LocationRequest(); 
    //locationRequest.setInterval(7500); 
    //locationRequest.setFastestInterval(5000); 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);*/ 


    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
} 


/** 
* Manipulates the map once available. 
* This callback is triggered when the map is ready to be used. 
* This is where we can add markers or lines, add listeners or move the camera. In this case, 
* we just add a marker near Sydney, Australia. 
* If Google Play services is not installed on the device, the user will be prompted to install 
* it inside the SupportMapFragment. This method will only be triggered once the user has 
* installed Google Play services and returned to the app. 
*/ 
@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     return; 
    } 
    mMap.setMyLocationEnabled(true); 

    Location locationActual = locationManager.getLastKnownLocation(provider);; 
    if(locationActual != null) { 
     // Getting latitude of the current location 
     double latitude = locationActual.getLatitude(); 
     // Getting longitude of the current location 
     double longitude = locationActual.getLongitude(); 
     // Creating a LatLng object for the current location 
     myPosition = new LatLng(latitude, longitude); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition)); 
     mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 16)); 
     } 
    } 


@Override 
public void onLocationChanged(Location location) { 
    Log.i("TESTTAG", "onLocationChanged called"); 
    LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude()); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition)); 
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 16)); 
} 



@Override 
public void onStatusChanged(String s, int i, Bundle bundle) { 

} 

@Override 
public void onProviderEnabled(String s) { 

} 

@Override 
public void onProviderDisabled(String s) { 

} 

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

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     return; 
    } 
    locationManager.requestLocationUpdates(provider, 400, 1, this); 

} 

@Override 
protected void onPause() { 
    super.onPause(); 
    locationManager.removeUpdates(this); 

} 

private class CityAsyncTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... urls) { 
     String result = ""; 
     URL url; 
     HttpURLConnection urlConnection = null; 

     try { 
      url = new URL(urls[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      InputStream in = urlConnection.getInputStream(); 
      InputStreamReader reader = new InputStreamReader(in); 
      int data = reader.read(); 
      while (data != -1){ 

       char current = (char) data; 
       result += current; 
       data = reader.read(); 
      } 
      return result; 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 

    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 

     try { 
      String mensaje = ""; 
      JSONObject jsonObject = new JSONObject(result); 
      String wetherInfo = jsonObject.getString("wether"); 

      JSONArray arr = new JSONArray(wetherInfo); 
      for (int i = 0; i < arr.length(); i++) { 
        JSONObject jsonPart = arr.getJSONObject(i); 
        String main = jsonObject.getString("main"); 
        String description = jsonObject.getString("description"); 
        if (main != "" && description != "") { 
         mensaje += main + " " + description + "\n\r"; 

        } 
       } 
      if(mensaje != ""){ 
       climaText.setText(mensaje); 
      } 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

    } 
} 

public void obtenerClima(){ 

    CityAsyncTask task = new CityAsyncTask(); 
    task.execute("http://api.openweathermap.org/data/2.5/weather?q=London,uk"); 

} 

public void startDialogReporte(View view) { 
    AlertDialog.Builder mBuilder = new AlertDialog.Builder(MapsActivity.this); 
    View mView = getLayoutInflater().inflate(R.layout.dialog_reporte,null); 
    mBuilder.setView(mView); 
    AlertDialog dialog = mBuilder.create(); 
    dialog.show(); 

} 

public void starDialogClima(View view){ 
    AlertDialog.Builder mBuilder = new AlertDialog.Builder(MapsActivity.this); 
    View mView = getLayoutInflater().inflate(dialog_clima,null); 
    obtenerClima(); 
    mBuilder.setView(mView); 
    AlertDialog dialog = mBuilder.create(); 
    dialog.show(); 

} 

}

manifeste dans le cas où vous en avez besoin

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.naluapp.naluapp"> 

    <!-- 
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use 
     Google Maps Android API v2, but you must specify either coarse or fine 
     location permissions for the 'MyLocation' functionality. 
    --> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 

    <uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" /> 

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



    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:roundIcon="@mipmap/ic_launcher_round" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme" 
     android:fullBackupContent="true"> 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" 
      android:theme="@style/AppTheme.NoActionBar"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <!-- 
      The API key for Google Maps-based APIs is defined as a string resource. 
      (See the file "res/values/google_maps_api.xml"). 
      Note that the API key is linked to the encryption key used to sign the APK. 
      You need a different API key for each encryption key, including the release key that is used to 
      sign the APK for publishing. 
      You can define the keys for the debug and release targets in src/debug/ and src/release/. 
     --> 
     <meta-data 
      android:name="com.google.android.geo.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> 

</manifest> 

Et mon dialogue pour la météo n'a qu'un affichage.

+0

Copie possible de [Qu'est-ce qu'une exception NullPointerException, et comment la réparer?] (Https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) –

Répondre

0

Dans le résultat JSON, "temps" est un tableau comme celui-ci:

"weather": [ 
     { 
      "id": 804, 
      "main": "Clouds", 
      "description": "overcast clouds", 
      "icon": "04d" 
     } 
    ] 

vous devez donc obtenir le tableau de temps comme ceci:

JSONArray weatherArr = jsonObject.getJSONArray("weather"); 

Puis boucle à travers weatherArr

+0

Pour une raison quelconque, le proble m continue à apparaître –