当前位置: 首页 > 知识库问答 >
问题:

我的应用程序无法登录,没有任何可能的解释

容鸿畴
2023-03-14

应用程序只是不会移动通过登录页面和错误指向一个内置的文档

我的代码

public class WeatherActivity extends AppCompatActivity {

    final int REQUEST_CODE = 123;
    //the openweather url to be used
    final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
    //the API key
    final String APP_ID = "c9e6cb73daaf09d1bf0d1502d964bf60";
    //time between location update (5000 milliseconds or 5 seconds)
    final long MIN_TIME = 5000;
    //Distance between location in metres
    final float MIN_DISTANCE = 1000;
    final String TAG = "WeatherApp";

    //For the app to detect the user's location,
    //we set the LOCATION_PROVIDER
    String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;


    //declare the variables to be linked to the layout
    TextView mTemperature;
    TextView mCity;
    ImageView mWeatherImage;

    //declare the LocationListener and LocationManager
    LocationManager mLocationManager;
    LocationListener mLocationListener;

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

        //Link the elements in the Layout here
        mCity = (TextView) findViewById(R.id.locationFetching);
        mTemperature = (TextView) findViewById(R.id.tempereatureView);
        mWeatherImage = (ImageView) findViewById(R.id.weatherImage);
        ImageButton ChangeCityButton = (ImageButton) findViewById(R.id.changeCityButton);


        //The Intent method used below is mostly used for switching between Activities
        ChangeCityButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent changeCityIntent = new Intent(WeatherActivity.this, ChangeCityController.class);
               // finish();
                startActivity(changeCityIntent);
            }
        });
    }


    //the onResume method is one of android lifecycle method
    //that starts/execute after the onCreate method
    @Override
    protected void onResume() {
        super.onResume();

        //retrieving the city name passed in the
        //ChangecityController
        //City was used in the PutExtra method in changeCity
        Intent myIntent = getIntent();
        String city =myIntent.getStringExtra("City");

        //if the user does not enter a particular city
        //retrieve user current city
        if(city != null) {
            getWeatherForNewLocation(city);
        } else {
            getWeatherForCurrentLocation();
        }
    }

    //The method to retrieve any city entered by the user
    private void getWeatherForNewLocation(String city) {
        //the request params passes in the required parameters to retrieve data using the API
        //The openWeatherMap API being used in this project, "q" and acity's name
        //is to be assigned to iy
        RequestParams params = new RequestParams();
        params.put("q", city);
        params.put("appid", APP_ID);
        networkingCalls(params);
    }

    //  get weather situation for current city -getWeatherForCurrentCityHere()
    private void getWeatherForCurrentLocation() {
        //create an instance of LocationManager
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //the Location listener does the checking of the location for update
        mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.d(TAG, "onLocationChanged: callback received");

                //get the longitude and latitude of current locaion
                //stored as a string
               String Longitude =  String.valueOf(location.getLongitude());
              String Latitude =  String.valueOf(location.getLatitude());

                Log.d(TAG, "onLocation Latitude is: " + Latitude);
                Log.d(TAG, "onLocationChanged: longitude " + Longitude);

                RequestParams params =  new RequestParams();

                params.put("lat", Latitude);
                params.put("lon", Longitude);
                params.put("appid", APP_ID);

                networkingCalls(params);

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {
                Log.d(TAG, "onProviderDisabled: callback");

            }
        };

        //REQUEST A LOCATION UPDATE PASSING THE LOCATION PROVIDER TO BE USED, MIN TIME,
        // MIN DISTANCE AND mLISTENER as the receiver
        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.
            //request permissions to use the user's device GPS
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
            return;
        }
        mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
    }


    //the override method below gives the result of the
    // permission request to use the user's GPS
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        //check to see if the request code matches the Request Code we gave
        //during the request
        if(requestCode == REQUEST_CODE){
            if(grantResults.length> 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Log.d(TAG, "onRequestPermissionsResult(): Granted!");
                getWeatherForCurrentLocation();
            }else{
                Log.d(TAG, "onRequestPermissionsResult: Permission Denied");
            }
        }
    }


    //create the networkingCalls method here
    //this method, we implement an HttpRequest, using it to make a Get request
    private void networkingCalls(RequestParams params){
        AsyncHttpClient client = new AsyncHttpClient();

        //the Json object handler is used to notify whether the Getrequest failed or was successful
        //the json response hanler receive 2 messages - onSucess and onFailure
        //both methods are declared below
        client.get(WEATHER_URL, params, new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response){
                Log.d(TAG, "onSuccess: " + response.toString());
                // call the json from the WeatherDataModel
                WeatherDataModel weatherData = WeatherDataModel.fromJson(response);
                updateUI(weatherData);
            }

            @Override
            public void onFailure(int statuscode, Header[] headers, Throwable e, JSONObject response){
                Log.e(TAG, "onFailure: "+ e.toString());
                Log.d(TAG, "Status code: " + statuscode);
                Toast.makeText(WeatherActivity.this, "Request failed", Toast.LENGTH_SHORT).show();

            }

        });
    }

    private void updateUI(WeatherDataModel weather){
        mTemperature.setText(weather.getTemperature());
        mCity.setText(weather.getCity());

        int resourceID = getResources().getIdentifier(weather.getIconname(), "drawable", getPackageCodePath());
        mWeatherImage.setImageResource(resourceID);
    }

    //This code below frees up memory
    //when mListener is not in use and it is automatically generated
    @Override
    protected void onPause() {
        super.onPause();

        if(mLocationManager != null) mLocationManager.removeUpdates(mLocationListener);
    }
}

public class WeatherDataModel {

    private String mTemperature;
    private String mCity;
    private String mIconname;
    private int mCondition;


    //create a weatherdatamodel fromJson:
    public static  WeatherDataModel fromJson(JSONObject jsonObject) {
        WeatherDataModel weatherData = new WeatherDataModel();
        //we surround the json parsing code with a try-catch statement
        //to handle errors like nan and empty values
        try {
            //get json object called -id, that is nested oin an object "0", thats also nested in an array called weather
            weatherData.mCondition = jsonObject.getJSONArray("weather").getJSONObject(0).getInt("id");
            weatherData.mCity = jsonObject.getString("name");
            weatherData.mIconname = updateWeatherIcon(weatherData.mCondition);

            double temp = jsonObject.getJSONObject("main").getDouble("temp") - 273.15;

            int rdValue = (int) Math.rint(temp);

            weatherData.mTemperature= Integer.toString(rdValue);
            return weatherData;
        }catch (JSONException e){
            e.printStackTrace();

            return null;
        }
    }


    private static String updateWeatherIcon(int condition) {

        if (condition >= 0 && condition < 300) {
            return "tstorm1";
        } else if (condition >= 300 && condition < 500) {
            return "light_rain";
        } else if (condition >= 500 && condition < 600) {
            return "shower3";
        } else if (condition >= 600 && condition <= 700) {
            return "snow4";
        } else if (condition >= 701 && condition <= 771) {
            return "fog";
        } else if (condition >= 772 && condition < 800) {
            return "tstorm3";
        } else if (condition == 800) {
            return "sunny";
        } else if (condition >= 801 && condition <= 804) {
            return "cloudy2";
        } else if (condition >= 900 && condition <= 902) {
            return "tstorm3";
        } else if (condition == 903) {
            return "snow5";
        } else if (condition == 904) {
            return "sunny";
        } else if (condition >= 905 && condition <= 1000) {
            return "tstorm3";
        }

        return "dunno";
    }

    //create a Get() for the variable created, so it can be retrieved in the weatherActivity

    public String getTemperature() {
        return mTemperature + "°";
    }

    public String getCity() {
        return mCity;
    }

    public String getIconname() {
        return mIconname;
    }
}

共有1个答案

荣德厚
2023-03-14

尝试先检查JSON对象是否存在:

if (jsonObjectjsonObject.getJSONArray("weather").getJSONObject(0).has("id")) {
        weatherData.mCity = jsonObject.getString("name");
        weatherData.mIconname = updateWeatherIcon(weatherData.mCondition);
    }
 类似资料:
  • 我无法在电脑或iPhone 7上的iOS模拟器上登录我的应用程序(我可以加载expo并进入登录/注册屏幕)。几天前还不错,今天就停了。。我没有接触到任何与我收到的错误有关的代码。在模拟器上,我访问了localhost:19001,它显示React Native packager正在运行。 以下是我在终端中遇到的错误: 取数错误 {"行": 22374,"列": 29,"源URL":"http://

  • 应用程序崩溃,我会得到以下错误: 致命异常:主进程:com.example.ayyan.JellyBeanEstimator,pid:2960 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.ayyan.JellyBeanEstimator/com.example.ayyan.JellyBeanEstimator.MainAc

  • 我正在研究React应用程序与KeyCloak的集成。我已经在本地计算机上安装了keycloak服务器版本11.0.2。我能够访问管理登录并创建管理用户。我还使用keycloak创建了一个具有凭据的自定义客户端和用户。我的react应用程序是在我的机器的端口9000上托管的,而keycloak是在8080(默认)端口上托管的。现在,当我重定向到我的应用程序URL时,它会自动重定向到下面的URL:

  • 问题内容: 在我的应用程序中,我使用jsapi实现了Google注销。 现在,我需要在我的应用程序中单击一个按钮的同时从Google登出该用户。如何使用JavaScript实现此功能,或者至少每次用户登录时它都必须询问Google登录页面。 我已经尝试过,但是似乎没有用。 问题答案: OAuth概述:他/她说的用户是他/她吗? 我不确定您是否使用OAuth来登录Stack Overflow,例如“

  • 我有两个文本框username和Password,它们目前存在于JSP中,现在我想把它转换成AngularJS SPA程序。登录表单或索引页由用户名、密码、输入时间、输出时间和重置组成。表单调用Java程序来存储这些值或验证凭据。我被困在如何在现有的应用程序中使用路由。任何帮助都将不胜感激!

  • 简短版本: 我试图检测我的麦克风何时被像不和谐这样的程序捕获,最好是在Python中,但是我不知道如何做到这一点。有什么建议吗? 长版本: 我试图编写一个程序,每当我的麦克风被使用时,它就会打开“开机”灯。通常情况下,这要么是为了不和谐,要么是为了抽搐。这也是视窗系统已经监控的东西(视窗10),因为它在通知托盘中显示一个麦克风图标,并告诉你哪些程序正在使用你的麦克风。基本上,每当图标通知打开时,我