【问题标题】:JSON output is not appearing in the logcatJSON 输出未出现在 logcat 中
【发布时间】:2018-10-21 20:03:46
【问题描述】:

我一直在通过在线课程学习 android studio,但遇到了问题。我正在使用 James Smith 的 Android 异步 Http 客户端的依赖项制作天气应用程序,但无法获取位置更新。我只在 logcat 中调用 onResume() 和 onPaused() 方法。我还使用 gps 提供商和网络提供商的粗略位置以及 gps 和网络提供商的精细位置。我的导师建议使用网络提供商并获取最后一个位置以使事情正常运行,但是当我第二天编译完全相同的代码时,它不起作用。我已经在清单文件中提到了 Internet 和访问精细位置的权限。我的手机(OnePlus 3)也启用了位置和互联网,并且已经获得了手机的许可。 android studio 也给我一个关于 [Location lastLocation = mlocationManager.getLastKnownLocation(LOCATION_PROVIDER)] 部分的错误。此外,我对编码还很陌生,所以如果有人能用简单的话向我解释一下,我将不胜感激。

这是代码。

public class WeatherController extends AppCompatActivity {

        // Constants:
        final int REQUEST_CODE = 123;
        final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";

        // App ID to use OpenWeather data
        final String APP_ID = "a_______________96";
        // Time between location updates (5000 milliseconds or 5 seconds)
        final long MIN_TIME = 5000;
        // Distance between location updates (1000m or 1km)
        final float MIN_DISTANCE = 1000;

        // TODO: Set LOCATION_PROVIDER here:

        String LOCATION_PROVIDER = LocationManager.NETWORK_PROVIDER;


        // Member Variables:
        TextView mCityLabel;
        ImageView mWeatherImage;
        TextView mTemperatureLabel;

        // TODO: Declare a LocationManager and a LocationListener here:

        LocationManager mLocationManager;
        LocationListener mLocationListener;


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

            // Linking the elements in the layout to Java code
            mCityLabel = (TextView) findViewById(R.id.locationTV);
            mWeatherImage = (ImageView) findViewById(R.id.weatherSymbolIV);
            mTemperatureLabel = (TextView) findViewById(R.id.tempTV);
            ImageButton changeCityButton = (ImageButton) findViewById(R.id.changeCityButton);


            // TODO: Add an OnClickListener to the changeCityButton here:

        }


        // TODO: Add onResume() here:

        @Override
        protected void onResume() {
            super.onResume();
            Log.d("Clima", "onResume() called");
            Log.d("Clima", "Getting weather for current location");
            getWeatherForCurrentLocation();
        }


        // TODO: Add getWeatherForNewCity(String city) here:


        // TODO: Add getWeatherForCurrentLocation() here:

        private void getWeatherForCurrentLocation() {
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            mLocationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Location lastLocation = mLocationManager.getLastKnownLocation(LOCATION_SERVICE);
                    Log.d("Clima", "onLocationChanged() callback received");
                    String longitude = String.valueOf(location.getLongitude());
                    String latitude = String.valueOf(location.getLatitude());

                    Log.d("Clima", "Longitude is: " + longitude);
                    Log.d("Clima", "Latitude is: " + latitude);

                    RequestParams params = new RequestParams();
                    params.put("lat", latitude);
                    params.put("lon", longitude);
                    params.put("appid", APP_ID);
                    letsDoSomeNetworking(params);

                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {
                    Log.d("Clima","onStatusChanged() called");
                }

                @Override
                public void onProviderEnabled(String s) {
                    Log.d("Clima", "onProviderEnabled() called");
                }

                @Override
                public void onProviderDisabled(String s) {
                    Log.d("Clima", "onProviderDisabled() callback received");

                }
            };
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#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 Activity#requestPermissions for more details.
                ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);

                return;
            }

            mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if(requestCode == REQUEST_CODE) {
                if(grantResults.length > 0 && grantResults[0] ==  PackageManager.PERMISSION_GRANTED)
                {
                    Log.d("Clima", "onRequestPermissionsResult() permission granted!");
                    getWeatherForCurrentLocation();
                } else {
                    Log.d("Clima", "onRequestPermissionsResult() permission denied!");
                }
            }
        }

        // TODO: Add letsDoSomeNetworking(RequestParams params) here:

        private void letsDoSomeNetworking(RequestParams params) {
            AsyncHttpClient client = new AsyncHttpClient();

            client.get(WEATHER_URL, params , new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                Log.d("Clima","Success! JSON: " + response.toString());
                }
                @Override
                public void onFailure(int statusCode,  Header[] headers, Throwable e , JSONObject response) {
                    Log.e("Clima", "Fail" + e.toString());
                    Log.d("Clima", "StatusCode: " + statusCode);
                    Toast.makeText(WeatherController.this, "Request failed", Toast.LENGTH_SHORT).show();
                }
            });

        }

        // TODO: Add updateUI() here:



        // TODO: Add onPause() here:
        @Override
        protected void onPause(){
            super.onPause();
            Log.d("Clima", "onPause() callback received ");
            Log.d("Clima","Weather data gathering stopped.");
        }
    }

【问题讨论】:

  • 给定 url 无效键的错误。
  • 您是否正确请求位置访问权限?您必须在 Manifest 文件中指定权限,并在运行时根据您设备的操作系统要求提供权限。检查这个 - stackoverflow.com/questions/40142331/…

标签: java android json android-studio location


【解决方案1】:
  1. 您将最小距离设置为 1000m,也许设置一个较小的值并尝试步行几米,以便 onLocationChanged() 可以接收回调。重新启动您的应用也应该可以工作。
  2. 使用LocationManager等系统服务时记得注销,否则可能导致内存泄漏。
  3. 您可以请求更新 onCreate()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2012-12-15
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多