2016-11-19 21 views
0

Я могу получить текущую температуру погоды от последнего известного местоположения пользователей и отобразить ее в текстовом виде. Как я могу также показать местоположение пользователя, на котором я получаю информацию о погоде? Я использую OpenWeather для моего API.Как отобразить местоположение пользователя Если я уже могу отображать текущую погоду? (Android)

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 

    private static final String APP_ID = "80e4eede56844462ef3cdc721208c31f"; 

    private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1; 
    private GoogleApiClient googleApiClient; 

    private TextView textView; 


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

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

     if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 
        PERMISSION_ACCESS_COARSE_LOCATION); 
     } 

     googleApiClient = new GoogleApiClient.Builder(this, this, this).addApi(LocationServices.API).build(); 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
     switch (requestCode) { 
      case PERMISSION_ACCESS_COARSE_LOCATION: 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        // All good! 
       } else { 
        Toast.makeText(this, "Need your location", Toast.LENGTH_SHORT).show(); 
       } 

       break; 
     } 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     if (googleApiClient != null) { 
      googleApiClient.connect(); 
     } 
    } 

    @Override 
    protected void onStop() { 
     googleApiClient.disconnect(); 
     super.onStop(); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     Log.i(MainActivity.class.getSimpleName(), "Connected to Google Play Services"); 

     if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 

      double lat = lastLocation.getLatitude(), lon = lastLocation.getLongitude(); 
      String units = "imperial"; 
      String url = String.format("http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s", 
        lat, lon, units, APP_ID); 
      new GetWeatherTask(textView).execute(url); 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!"); 
    } 

    private class GetWeatherTask extends AsyncTask<Object, Object, Double> { 
     private TextView textView; 


     public GetWeatherTask(TextView textView) { 
      this.textView = textView; 
     } 

     @Override 
     protected Double doInBackground(Object... strings) { 

      double weather = 0; 

      try { 
       URL url = new URL((String) strings[0]); 
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

       InputStream stream = new BufferedInputStream(urlConnection.getInputStream()); 
       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream)); 
       StringBuilder builder = new StringBuilder(); 

       String inputString; 
       while ((inputString = bufferedReader.readLine()) != null) { 
        builder.append(inputString); 
       } 

       JSONObject topLevel = new JSONObject(builder.toString()); 
       JSONObject main = topLevel.getJSONObject("main"); 
       weather = main.getDouble("temp"); 


       urlConnection.disconnect(); 
      } catch (IOException | JSONException e) { 
       e.printStackTrace(); 
      } 
      return weather; 
     } 

     @Override 
     public void onPostExecute(Double temp) { 
       textView.setText("Weather temperature is " + temp); 

     } 

    } 
} 
+0

Ум, положите место в «TextView». – CommonsWare

ответ

0

http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%s Используйте апи вместо того, чтобы получить всю информацию о месте, включая имя, темп и т.д.

Для топонима: Вы должны извлечь данные в формате JSON как:

JSONObject js = new JSONObject(response) //the resp you are getting 
String placeName = js.getString("name") 

Как это вы может извлечь больше подробностей о месте.

EDIT: С помощью этого API вы можете получить температуру как:

double temp = js.getJSONObject("main").getDouble("temp") 

Для установки значения в TextView, вы можете использовать:

TextView tw1 = (TextView) findViewById(R.id.x) //Your textView's id 
tw1.setText(placeName) 

Для установки дважды: TW1. SetText (String.valueOf (температура));

Надеюсь, это поможет!

+0

Привет, когда я использую эту ссылку, не изменяя ничего кроме нее, температура отображается как 0.0. –

+0

Вы должны работать в новом формате, так как возвращаемые данные отличаются от того, что вы делали до – Swr7der

+0

Есть ли способ, которым я могу использовать только ту же ссылку и формат, которые мне нужно получить только в городе? –

 Смежные вопросы

  • Нет связанных вопросов^_^