首页 > 解决方案 > 将改造响应从一个类发送到一个活动

问题描述

我正在开发一个天气应用程序,我的所有位置方法都在它自己的类中,如果位置不为空,则使用其中一种方法,然后我使用改造从 URL 中检索 JSON 数据,现在我需要发送该数据从我的 LocationDataService 类返回到 MainActivity

        public class MainActivity extends AppCompatActivity {
        TextView currentTempTextView;
        private static final String TAG = "MyActivity";
        private ArrayList<Weather> weatherLsit;
        public static int REQUEST_PERMISSION=1;
        private int LOCATION_REQUEST_CODE = 1001;
        private RecyclerView recyclerView;
        private EditText zipCodeEditText;
        LocationDataService locationDataService = new LocationDataService(MainActivity.this, 
    this, currentTempTextView);
        FusedLocationProviderClient fusedLocationProviderClient;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            currentTempTextView = findViewById(R.id.current_temp_text_view);
            setContentView(R.layout.activity_main);
            recyclerView = findViewById(R.id.hourly_recycle_view);
            currentTempTextView = findViewById(R.id.current_temp_text_view);
    
            if (locationDataService.hasLocationPermission() == true){
                locationDataService.getLastLocation();
            } else {
                locationDataService.requestLocationPermission();
            }
            weatherLsit = new ArrayList<>();
            weatherLsit.add(new Weather(10, 6, R.drawable.cloudy_icon));
            weatherLsit.add(new Weather(15, 7, R.drawable.cloudy_icon));
            weatherLsit.add(new Weather(10, 8, R.drawable.cloudy_icon));
            weatherLsit.add(new Weather(60, 9, R.drawable.cloudy_icon));
            weatherLsit.add(new Weather(80, 10, R.drawable.cloudy_icon));
            weatherLsit.add(new Weather(20, 12, R.drawable.cloudy_icon));
            weatherLsit.add(new Weather(13, 12, R.drawable.cloudy_icon));
            setAdapter();
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 
    @NonNull int[] grantResults) {
            if (requestCode == LOCATION_REQUEST_CODE) {
                if (grantResults.length > 0 && grantResults[0] == 
   PackageManager.PERMISSION_GRANTED) {
                    //PERMISSION GRANTED
                    locationDataService.getLastLocation();
                } else {
                    //PERMISSION DENIED
                    Toast.makeText(this, "PLEASE GRANT PERMISSION", LENGTH_LONG).show();
                }
            }
        }
    
        private void setAdapter() {
            WeatherAdapter adapter = new WeatherAdapter(weatherLsit);
            RecyclerView.LayoutManager layoutManager = new 
    LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(adapter);
            }
        }

这是我获得位置的另一堂课,我将位置传递给改造获得响应

        public class LocationDataService extends AppCompatActivity {
        private String lat;
        private String lon;
        private static final String TAG = "MyActivity";
        private FusedLocationProviderClient fusedLocationProviderClient;
        private int LOCATION_REQUEST_CODE = 1001;
        Activity activity;
        Context context;
        TextView textView;
    
        public LocationDataService(Context context, Activity activity, TextView textView) {
            this.context = context;
            this.activity = activity;
            this.textView = textView;
        }
    
        public Boolean hasLocationPermission() {
            if (ContextCompat.checkSelfPermission(context, 
    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                return false;
            }
        }
    
    
        public void requestLocationPermission() {
            fusedLocationProviderClient = 
    LocationServices.getFusedLocationProviderClient(context);
            if (ContextCompat.checkSelfPermission(context, 
    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity, 
    Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    Log.d("MainActivity", "Ask Location Permission You Should accept");
                    ActivityCompat.requestPermissions(activity, new String[]. 
    {Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST_CODE);
                } else {
                    ActivityCompat.requestPermissions(activity, new String[]. 
    {Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST_CODE);
                }
            }
        }
    
        public void getLastLocation() {
            WeatherModel weatherModel = new WeatherModel();
            fusedLocationProviderClient = 
    LocationServices.getFusedLocationProviderClient(context);
            if (ActivityCompat.checkSelfPermission(context, 
    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(context, 
    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;
            }
            Task<Location> locationTask = fusedLocationProviderClient.getLastLocation();
            locationTask.addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
    
                    if (location != null) {
                        System.out.println(location);
                        String lat = location.getLatitude() + "";
                        String lon = location.getLongitude() + "";
                        String latLong = lat + "," + lon;
    
                        Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("https://api.weatherapi.com/v1/")
                                .addConverterFactory(GsonConverterFactory.create())
                                .build();
                        APICall apiCall = retrofit.create(APICall.class);
                        Call<WeatherModel> call = apiCall.getWeather((latLong));
                        call.enqueue(new Callback<WeatherModel>() {
                            @Override
                            public void onResponse(Call<WeatherModel> call, 
    Response<WeatherModel> response) {
                                if (response.code() != 200) {
                                    Toast.makeText(context, "There was a problem: " + 
    response.code(), Toast.LENGTH_SHORT).show();
                                }
                                System.out.println("Feels Like Is: " + 
     response.body().getCurrent().getFeelslikeF().toString());
                            }
                            @Override
                            public void onFailure(Call<WeatherModel> call, Throwable t) {
                                System.out.println("There was a problem!: onFaulure " + t);
                            }
                        });
                    } else if (location == null){
                       System.out.println("Location Does = Null");
                    }
                }
            });
            locationTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                }
            });
          }
        }

正如您可能会说的那样,我对 android dev 真的很陌生,我对这个问题感到非常沮丧。这是我第一个严肃的应用程序项目,我尝试了很多不同的方法,但没有任何效果。最重要的是,位置随机返回 null,有时它会完美运行,有时它会返回 null 并强制退出。任何帮助将不胜感激。谢谢你!!

标签: javaandroidfusedlocationproviderapi

解决方案


推荐阅读