2017-09-19 1 views
-1

Ich arbeite gerade an einer Android Studio App. Ich habe eine Schaltfläche hinzugefügt, die einen Dialog öffnet, in dem ich das Wetter der Stadt des Benutzers anzeigen muss. Im Moment habe ich eine Menge Probleme damit. Zum Beispiel ist ein Fehler wie dieser aufgetreten und ich weiß, dass diese Frage bereits beantwortet wurde, aber ich habe immer noch viele Probleme damit.Versuch, die virtuelle Methode 'int java.lang.String.length()' für eine Nullobjekt-Referenz aufzurufen. Wie kann ich das beheben?

java.lang.NullPointerException: Der Versuch, virtuelle Methode ‚int java.lang.String.length()‘ auf ein Null-Objekt Referenz

Abgesehen davon aufzurufen, muss ich etwas anderes zu tun, es zu machen Arbeit?

Dies ist der Code, den ich habe:

public class MapsActivity erweitert FragmentActivity implementiert OnMapReadyCallback, Location {

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(); 

} 

}

Manifest auf, falls Sie es

<?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> 

Und mein Dialog für das Wetter hat nur eine Textvorschau.

+0

Mögliches Duplikat von [Was ist eine NullPointerException und wie behebe ich sie?] (Https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-fix-it) –

Antwort

0

Im JSON Ergebnis "Wetter" ist ein Array wie folgt aus:

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

so müssen Sie wie so das Wetter Array erhalten:

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

Dann Schleife durch weatherArr

+0

Aus irgendeinem Grund das Problem m erscheint immer –

Verwandte Themen