Problème Variable Android studio

Fermé
fares161121 Messages postés 12 Date d'inscription samedi 20 novembre 2021 Statut Membre Dernière intervention 9 juin 2022 - Modifié le 6 juin 2022 à 20:31
BunoCS Messages postés 15472 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 25 mars 2024 - 10 juin 2022 à 11:22
Bonjour j'ai un problème je n'arrive pas a remplacer les variables "latitude" et "longitude" par "lat1" et "long1" pourriez vous m'aidez merci :)

CODE :

package com.example.meteogpsipbtc;

import ...

public class MainActivity extends AppCompatActivity {
    TextView tempTextView;
    TextView timeTextView;
    TextView bitTextView;
    TextView AddressText;
    private LocationRequest locationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // get the reference of TextView's
        tempTextView = (TextView) findViewById(R.id.temp);
        timeTextView = (TextView) findViewById(R.id.time);
        bitTextView = (TextView) findViewById(R.id.bitcoin);
        AddressText = findViewById(R.id.addressText);

        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(5000);
        locationRequest.setFastestInterval(2000);

        Button search = (Button) findViewById(R.id.search);

        // Réagir au click sur le bouton SEARCH :
        search.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                new MeteoTask().execute(); }
        });

    }

    private class MeteoTask extends AsyncTask<String, Void, String[]> {

        public  String callHttpsAPI(String urlString) throws IOException, JSONException {
            HttpsURLConnection urlConnection = null;
            URL url = new URL(urlString);
            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(10000 /* milliseconds */ );
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.setDoOutput(true);
            urlConnection.connect();

            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuilder sb = new StringBuilder();

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

            String jsonString = sb.toString();
            System.out.println("JSON: " + jsonString);

            return jsonString;
        }

        protected void onPreExecute(){
            super.onPreExecute();
        }

        @Override
        protected String[] doInBackground(String... args) {
            String[] result = new String[3];
            String ucd = "https://api.coindesk.com/v1/bpi/currentprice.json";

            try {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

                        LocationServices.getFusedLocationProviderClient(MainActivity.this)
                                .requestLocationUpdates(locationRequest, new LocationCallback(){
                                    @Override
                                    public void onLocationResult(@NonNull LocationResult locationResult) {
                                        super.onLocationResult(locationResult);

                                        LocationServices.getFusedLocationProviderClient(MainActivity.this)
                                                .removeLocationUpdates(this);

                                        if (locationResult != null && locationResult.getLocations().size() >0){

                                            int index = locationResult.getLocations().size() - 1;
                                            double la1 = locationResult.getLocations().get(index).getLatitude();
                                            double long1 = locationResult.getLocations().get(index).getLongitude();

                                            AddressText.setText("Latitude: "+ la1 + "\n" + "Longitude: "+ long1);
                                        }
                                    }
                                }, Looper.getMainLooper());

                    }

                //Récupération résultat requete URL  ucd dans le 1er tabeau
                result[1] = this.callHttpsAPI(ucd);

                //Récupération résultat requete URL myip pour l'interger dans URL ip dans le 2eme tabeau
                String myip ="https://api.ipify.org";
                String IP = this.callHttpsAPI(myip);
                String ip = "https://ipinfo.io/"+IP+"/geo";
                result[2] = this.callHttpsAPI(ip);

                //Récupération JSON ipinfo.io avec  @IP dynamique localisation
                JSONObject resReqWeb4 = new JSONObject(result[2]);
                //RECUPERATION du String loc ou il y a longitude et latitude
                String locip2 = resReqWeb4.getString( "loc");
                // Split pour récuperer long et lat séparer + affectation a variable
                String[] coordo = locip2.split(",");
                String latitude = coordo[0];
                String longitude = coordo[1];
                //Affectation des 2 nouvelles varaible latitude et longitude a LURL météo avec la localisation de l'IP
                String meteo = "https://api.open-meteo.com/v1/forecast?latitude="+latitude+"&longitude="+longitude+"&hourly=temperature_2m";
                result[0] = this.callHttpsAPI(meteo);


            } catch (IOException | JSONException e) {
                e.printStackTrace();
                String[] err = new String [1];
                err[0]="Exception: " + e.getMessage();
                return err;
            }
            return result;
        }
        // result c'est le JSON complet
        protected void onPostExecute(String[] result) {

            try {

                //Récupération du JSON @IP
                JSONObject resReqWeb6 = new JSONObject(result[2]);
                //RECUPERATION OBJET
                String mycity = resReqWeb6.getString( "city");


                //Récupération du JSON complet météo
                JSONObject resReqWeb = new JSONObject(result[0]);
                //On convertit le contenu de la case en string
                String string1 = resReqWeb.getJSONObject( "hourly").getJSONArray( "temperature_2m").getString(0);
                String string2 = resReqWeb.getJSONObject( "hourly").getJSONArray( "time").getString(0);
                //Mise a jour du TextView
                tempTextView.setText("Il faisait à "+mycity+": "+string1 +" °C ");
                timeTextView.setText(" le : "+string2);


                //Récupération du JSON bitcoin
                JSONObject resReqWeb2 = new JSONObject(result[1]);
                //Récupération OBJET bpi
                JSONObject bpi = resReqWeb2.getJSONObject("bpi");
                //Récupération de l'objet EUR
                JSONObject eur = bpi.getJSONObject("EUR");
                //Récupération du court du bitcoin
                double biteuro = eur.getDouble("rate_float");
                bitTextView.setText("Cours du BTC : "+ biteuro +" €");

            }

            catch (Exception e) {
                e.printStackTrace();
            }
            //Fin de la méthode onPostExecute

        }

    }
}
A voir également:

2 réponses

BunoCS Messages postés 15472 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 25 mars 2024 3 894
7 juin 2022 à 10:23
Hello,

Il va falloir être un peu plus explicite dans tes demandes...
Bon, j'imagine que tu parles de ça:
if (locationResult != null && locationResult.getLocations().size() >0){

    int index = locationResult.getLocations().size() - 1;
    double la1 = locationResult.getLocations().get(index).getLatitude();
    double long1 = locationResult.getLocations().get(index).getLongitude();

     AddressText.setText("Latitude: "+ la1 + "\n" + "Longitude: "+ long1);
}

Tu as déclaré des variable locales. Les variables locales ont une portée réduite au bloc dans lequel elles sont déclarées. Autrement dit, sorti de la condition if, ces variables sont détruites. Il faut que tu utilises des variables de classe

https://rmdiscala.developpez.com/cours/LesChapitres.html/Java/Cours3/Chap3.1.htm
0
fares161121 Messages postés 12 Date d'inscription samedi 20 novembre 2021 Statut Membre Dernière intervention 9 juin 2022
9 juin 2022 à 11:56
Bonjour,

Merci pour ta réponses mais j'ai tester des trucs mais rien marche est ce tu pourrais m'aider merci :)
0
BunoCS Messages postés 15472 Date d'inscription lundi 11 juillet 2005 Statut Modérateur Dernière intervention 25 mars 2024 3 894
10 juin 2022 à 11:22
T'aider, oui, pas de soucis. Par contre, comme dit plus haut
Il va falloir être un peu plus explicite dans tes demandes...
0