尝试发出GET请求时,Android Studio应用程序崩溃

时间:2020-09-22 15:26:54

标签: java android

我很高兴能在android studio中开发我的第一个应用程序。不幸的是,每当我尝试使用Android Volley发出API Get请求时,我的应用程序就会崩溃。我项目的目标是制作一个可根据当前天气更改壁纸的应用程序。这是我来自MainActivity.java的当前代码。任何建议都将不胜感激,因为我仍然是一个学习者。

package com.example.wall_paper_v03;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private TextView requestResult;
    public String lon = "1";
    public String lat = "1";

    private static final int REQUEST_CODE_LOCATION_PERMISSION = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION_PERMISSION);
        }else{
            getLocation();
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        Button Request_Button = findViewById(R.id.Request_Button);
        TextView requestResult = findViewById(R.id.ResultText);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setWallpaper();
            }
        });
        Request_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequest();
            }
        });
    }
    private void setWallpaper() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.minimal_day_clear);
        WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
        try{
            manager.setBitmap(bitmap);

        } catch (IOException e) {
            Toast.makeText(this, "Error!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == REQUEST_CODE_LOCATION_PERMISSION && grantResults.length > 0){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                getLocation();
            }else{
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void getLocation(){
        LocationRequest locationRequest = new LocationRequest();
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(3000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationServices.getFusedLocationProviderClient(MainActivity.this).requestLocationUpdates(locationRequest, new LocationCallback(){
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                LocationServices.getFusedLocationProviderClient(MainActivity.this).removeLocationUpdates(this);
                if(locationResult != null && locationResult.getLocations().size() > 0){
                    int latestLocationIndex = locationResult.getLocations().size() - 1;
                    double latitude = locationResult.getLocations().get(latestLocationIndex).getLatitude();
                    double longitude = locationResult.getLocations().get(latestLocationIndex).getLongitude();
                    lat = String.valueOf(latitude);
                    lon = String.valueOf(longitude);
                }

            }

        }, Looper.getMainLooper());
    }
    private void sendRequest() {
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        final String API = "&appid=INSERT API HERE";
        final String URL_PREFIX = "http://api.openweathermap.org/data/2.5/weather?lat=";
        final String second_part = "&lon=";

        String url = URL_PREFIX + lat + second_part + lon + API;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
             public void onResponse(String response) {
            if(response.length()>399){
                requestResult.setText(response.substring(0,400));
            }else{
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
            }


        }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                requestResult.setText("error! :(");
            }
        });
        queue.add(stringRequest);
    }
}

Logcat文件:

2020-09-22 10:43:59.181 1055-1259/? E/WifiVendorHal: getWifiLinkLayerStats(l.937) failed {.code = ERROR_NOT_SUPPORTED, .description = }
2020-09-22 10:43:59.996 18925-19005/com.example.wall_paper_v03 E/libc: Access denied finding property "persist.vendor.log.tel_dbg"
2020-09-22 10:44:00.000 1055-1182/? E/MtkDataShapingUtils: Exception openLteGateByDataShaping
2020-09-22 10:44:00.295 18925-18925/com.example.wall_paper_v03 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.wall_paper_v03, PID: 18925
    java.lang.StringIndexOutOfBoundsException: length=460; index=461
        at java.lang.String.substring(String.java:2032)
        at com.example.wall_paper_v03.MainActivity$4.onResponse(MainActivity.java:124)
        at com.example.wall_paper_v03.MainActivity$4.onResponse(MainActivity.java:121)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:7049)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:913)
2020-09-22 10:44:00.310 447-447/? E/lowmemorykiller: Error writing /proc/18925/oom_score_adj; errno=22
2020-09-22 10:44:00.336 1055-1193/? E/InputDispatcher: channel 'a14a2e8 com.example.wall_paper_v03/com.example.wall_paper_v03.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2020-09-22 10:44:00.535 10603-10685/? E/PBSessionCacheImpl: sessionId[46634087891863591] not persisted.
2020-09-22 10:44:02.185 1055-1259/? E/WifiVendorHal: getWifiLinkLayerStats(l.937) failed {.code = ERROR_NOT_SUPPORTED, .description = }
2020-09-22 10:44:04.591 1981-1981/? E/RegisteredServicesCache: Next Tag=services
2020-09-22 10:44:04.591 1981-1981/? E/RegisteredServicesCache: installedServices no uidString 
2020-09-22 10:44:04.591 1981-1981/? E/RegisteredServicesCache: installedServices contains uidString : 10036
2020-09-22 10:44:04.631 1981-1981/? E/RegisteredServicesCache: 1invalidateCache:WriteServiceStateToFile
2020-09-22 10:44:04.631 1981-1981/? E/RegisteredServicesCache:  Writing service state Data Always
2020-09-22 10:44:04.634 1981-1981/? E/RegisteredServicesCache: component namecom.google.android.gms/com.google.android.gms.nearby.mediums.nearfieldcommunication.NfcAdvertisingService
2020-09-22 10:44:04.635 1981-1981/? E/RegisteredServicesCache: component namecom.google.android.gms/com.google.android.gms.pay.hce.service.PayHceService
2020-09-22 10:44:04.638 10603-10603/? E/PodcastsMBService: com.android.bluetooth is not authorized to browse contents.
2020-09-22 10:44:04.639 1761-1761/? E/MediaBrowser: onConnectFailed for ComponentInfo{com.google.android.googlequicksearchbox/com.google.android.apps.gsa.staticplugins.mediabrowser.PodcastsMediaBrowserService}
2020-09-22 10:44:04.657 1761-1761/? E/MediaBrowser: onConnectFailed for ComponentInfo{com.amazon.avod.thirdpartyclient/com.amazon.avod.voicecontrols.service.PrimeVideoMediaService}
2020-09-22 10:44:04.683 1981-1981/? E/RegisteredServicesCache: 3updateStatusOfServices:WriteServiceStateToFile
2020-09-22 10:44:04.683 1981-1981/? E/RegisteredServicesCache:  Writing service state Data Always
2020-09-22 10:44:04.684 1981-1981/? E/RegisteredServicesCache: component namecom.google.android.gms/com.google.android.gms.nearby.mediums.nearfieldcommunication.NfcAdvertisingService
2020-09-22 10:44:04.684 1981-1981/? E/RegisteredServicesCache: component namecom.google.android.gms/com.google.android.gms.pay.hce.service.PayHceService
2020-09-22 10:44:04.734 1761-1761/? E/MediaBrowser: onConnectFailed for ComponentInfo{flipboard.boxer.app/flipboard.media.MediaPlaybackService}
2020-09-22 10:44:04.982 17306-17306/? E/Spotify: [main] onGetRoot: IGNORING request from untrusted package com.android.bluetooth
2020-09-22 10:44:04.996 1761-1761/? E/MediaBrowser: onConnectFailed for ComponentInfo{com.spotify.music/com.spotify.music.libs.mediabrowserservice.SpotifyMediaBrowserService}
2020-09-22 10:44:05.204 1055-1259/? E/WifiVendorHal: getWifiLinkLayerStats(l.937) failed {.code = ERROR_NOT_SUPPORTED, .description = }
2020-09-22 10:44:05.511 1055-1182/? E/MtkDataShapingUtils: Exception openLteGateByDataShaping

0 个答案:

没有答案