java—如何将值存储在全局变量中,并在活动的任何地方的任何方法中使用它

pgvzfuti  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(381)

我正在尝试建立一个天气应用程序。我有一个api链接,我把它作为字符串变量,它的作用域是全局的,我有另一个方法来获取经度和纬度。我想将这些纬度和经度值保存在范围为全局的变量中。当我在geocoder方法中提取纬度和经度值时(我的全局变量api link发生了变化,并给出了所需的结果,因为我将longtiude和latitude与作用域为全局的变量连接在一起。但一旦我放弃了这个方法,并尝试在另一个方法中使用我的api链接(我丢失了在geocoder方法中获得并连接的纬度和经度值),希望它能永久地改变我的全局变量值。
这是密码(我有4-5个文件,但我只粘贴在我实际工作的主要活动代码)如果我硬编码的纬度和经度值,我得到了想要的结果,但我只是想通过获得纬度和经度在这方面做得更好。

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Model>> {

    public static final int WEATHERLOADER = 1;
    RecyclerView recyclerView;
    WeatherAdapter mAdapter;
    List<Model> modelList;
    FusedLocationProviderClient fusedLocation;
    String latitude;
    String longit;
    Button getweather;

   String APILINK = "http://api.openweathermap.org/data/2.5/weather?lat=";

    String APIKEY = "&appid=5c161192e5aa828fc6a8896eddaf89e2";

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

        getweather = findViewById(R.id.getWeather);

        recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        modelList = new ArrayList<>();
        mAdapter = new WeatherAdapter(this, modelList);
        recyclerView.setAdapter(mAdapter);

        ConnectivityManager conn = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        if (conn!=null) {
            NetworkInfo networkInfo = conn.getActiveNetworkInfo();

            if (networkInfo!=null){
                LoaderManager loaderManager = getSupportLoaderManager();
                loaderManager.initLoader(WEATHERLOADER, null, this);
            }

        }

        fusedLocation = LocationServices.getFusedLocationProviderClient(this);

        getweather.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) {
                    wantLocation();
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
                }

            }

        });

    }

    private void wantLocation() {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        fusedLocation.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {

                Location location = task.getResult();

                if (location != null) {

                    try {

                        Geocoder geocoder = new Geocoder(
                                MainActivity.this, Locale.getDefault());

                        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

                        /*cityname.setText(Html.fromHtml("<font color='#6200EE'><b>City Name:</b><br></font>" + addresses.get(0).getAdminArea()));
                        longtitude.setText(Html.fromHtml("<font color='#6200EE'><b>Longtitude:</b><br></font>" + addresses.get(0).getLongitude()));
                        lattitude.setText(Html.fromHtml("<font color='#6200EE'><b>Lattitude:</b><br></font>" + addresses.get(0).getLatitude()));
                        countryname.setText(Html.fromHtml("<font color='#6200EE'><b>Country Name:</b><br></font>" + addresses.get(0).getCountryName()));

* /

                        APILINK = APILINK + addresses.get(0).getLatitude() + "&lon=" + addresses.get(0).getLongitude() + APIKEY;

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

                }
            }

        });

    }

    @NonNull
    @Override
    public Loader<List<Model>> onCreateLoader(int i, @Nullable Bundle bundle) {

        Toast.makeText(MainActivity.this, String.valueOf(APILINK), Toast.LENGTH_SHORT).show();

        return new WeatherLoader(this, APILINK);
    }

    @Override
    public void onLoadFinished(@NonNull Loader<List<Model>> loader, List<Model> modelList) {
        if (modelList!=null && !modelList.isEmpty()) {
            mAdapter = new WeatherAdapter(this, modelList);
            recyclerView.setAdapter(mAdapter);
        }

    }

    @Override
    public void onLoaderReset(@NonNull Loader<List<Model>> loader) {

    }
}
bis0qfac

bis0qfac1#

我不确定我是否完全理解这个问题/情况,但是从提供的代码来看,应该在oncomplete方法中正确修改apilink。如果尝试从其他类访问apilink,可以创建一个“getter”方法,该方法在调用时返回apilink:

public String getAPILINK() {
    return APILINK;
}

通过将字符串设置为getapilink(),可以在不同的类或方法中创建apilink的副本。
编辑1:要串联字符串,只需使用+运算符。这可能意味着问题出在别处。要排除故障,请尝试添加

System.out.println(APILINK);

到程序中的不同点,比如调用oncomplete之前和之后。如果附加了“&lon=”和apikey,但没有附加纬度和经度,那么问题是检索这些值。

相关问题