繁体   English   中英

即使我添加了条件,应用程序在没有互联网时也会崩溃

[英]App crashes when there is no internet even though I have added conditions to it

伙计们,我的应用程序在没有互联网时崩溃我在 MainActivity.java 中添加了以下代码

import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.firebase.messaging.FirebaseMessaging;

public class MainActivity extends AppCompatActivity {

String websiteURL = "https://animenerdyinfo.blogspot.com/"; // sets web url
private WebView webview;
SwipeRefreshLayout mySwipeRefreshLayout;
private LinearLayout noInternetLayout;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FirebaseMessaging.getInstance().subscribeToTopic("notifications");

    AdView adView = (AdView)findViewById(R.id.adView);
    AdRequest adRequest =new AdRequest.Builder().build();
    adView.loadAd(adRequest);

    noInternetLayout=findViewById(R.id.noInternetLayout);

    checknetwork();

    //Swipe to refresh functionality
    mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);

    mySwipeRefreshLayout.setOnRefreshListener(
            new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    webview.reload();
                }
            }
    );

    if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
        if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){

            Log.d("permission","permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            requestPermissions(permissions,1);
        }


    }

 //handle downloading

    webview.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {

            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setMimeType(mimeType);
            String cookies = CookieManager.getInstance().getCookie(url);
            request.addRequestHeader("cookie",cookies);
            request.addRequestHeader("User-Agent",userAgent);
            request.setDescription("Downloading file....");
            request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,URLUtil.guessFileName(url, contentDisposition, mimeType));
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getApplicationContext(),"Downloading File", Toast.LENGTH_SHORT).show();


        }
    });

}

private class WebViewClientDemo extends WebViewClient {
    @Override
    //Keep webview in app when clicking links
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        mySwipeRefreshLayout.setRefreshing(false);
    }
}

//set back button functionality
@Override
public void onBackPressed() { //if user presses the back button do this
    if (webview.isFocused() && webview.canGoBack()) { //check if in webview and the user can go back
        webview.goBack(); //go back in webview
    } else { //do this if the webview cannot go back any further

        new AlertDialog.Builder(this) //alert the person knowing they are about to close
                .setTitle("EXIT")
                .setMessage("Are you sure. You want to close this app?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setNegativeButton("No", null)
                .show();
    }
}

private void checknetwork(){
    ConnectivityManager connectivityManager= (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    NetworkInfo mobile=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isConnected()){
        webview.loadUrl("https://animenerdyinfo.blogspot.com/");
        webview.setVisibility(View.VISIBLE);
        noInternetLayout.setVisibility(View.INVISIBLE);
    }
    else if (mobile.isConnected()){
        webview.loadUrl("https://animenerdyinfo.blogspot.com/");
        webview.setVisibility(View.VISIBLE);
        noInternetLayout.setVisibility(View.INVISIBLE);
    }else{
        webview.setVisibility(View.INVISIBLE);
        noInternetLayout.setVisibility(View.VISIBLE);
    }
}

}

这在我的activitymain.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipeContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/webView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        tools:ignore="MissingConstraints" />

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

<LinearLayout
    android:visibility="invisible"
    android:id="@+id/noInternetLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffff"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <ImageView
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_marginTop="35dp"
        android:src="@drawable/oops_small"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No Internet"
        android:textSize="45sp"/>


</LinearLayout>

<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-2422938756578642/8442088186"
    tools:ignore="MissingConstraints">
</com.google.android.gms.ads.AdView>

</RelativeLayout>

这是我在 logcat 中得到的错误

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bestanimewallpapers, PID: 18953
java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.example.bestanimewallpapers/com.example.bestanimewallpapers.MainActivity}: 
java.lang.NullPointerException: Attempt to invoke virtual method 'void 
android.webkit.WebView.setVisibility(int)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void 
  android.webkit.WebView.setVisibility(int)' on a null object reference
    at com.example.bestanimewallpapers.MainActivity.checknetwork(MainActivity.java:154)
    at com.example.bestanimewallpapers.MainActivity.onCreate(MainActivity.java:53)
    at android.app.Activity.performCreate(Activity.java:6975)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6541) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
    I/zygote: Background concurrent copying GC freed 11556(1403KB) AllocSpace objects, 
    6(116KB) LOS objects, 50% free, 2MB/5MB, paused 3.884ms total 129.262ms
    W/ManagedChannelImpl: [{0}] Failed to resolve name. status={1}
    W/ManagedChannelImpl: [{0}] Failed to resolve name. status={1}
    E/EGL_emulation: tid 19029: swapBuffers(552): error 0x300d (EGL_BAD_SURFACE)

此代码在我的 AndroidManifest.xml 中

<uses-permission android:name="android.permission.INTERNET" />
<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

所以,任何人都可以告诉我我错在哪里并帮助我解决这个问题,我是这个东西的新手,如果你能用简单的方式告诉我会很棒

您忘记初始化webview

checknetwork方法调用之前在onCreate方法中添加以下行。

webview= (WebView)this.findViewById(R.id.webView);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM