0

I am using some code to test the connection, then display an alert, mypage where I added the functions:

import android.app.AlertDialog
import android.app.Application
import android.content.Context
import android.content.DialogInterface
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build


class connecttest: Application() {
     fun yesisav(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val nw = connectivityManager.activeNetwork?: return false
            val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
            return when {
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
                //for other device how are able to connect with Ethernet
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
                //for check internet over Bluetooth
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> true
                else -> false
            }
        } else {
            return connectivityManager.activeNetworkInfo?.isConnected ?: false
        }
    }

    fun displaymess(context: Context){
        // build alert dialog
        val dialogBuilder = AlertDialog.Builder(this)
        // set message of alert dialog
        dialogBuilder.setMessage("Do you want to close this application ?")
        // if the dialog is cancelable
        .setCancelable(false)
        // positive button text and action
                    .setPositiveButton("Proceed", DialogInterface.OnClickListener {
                        dialog, id -> finish()
                    })
        // negative button text and action
                .setNegativeButton("Continue", DialogInterface.OnClickListener {
                    dialog, id -> dialog.cancel()
                })
        // create dialog box
        val alert = dialogBuilder.create()
        alert.setTitle("AlertDialogExample")
        alert.show()
    }
}

in the activity :

val test=connecttest()
        if(!test.yesisav(this)){
            test.displaymess(this)
        }

the code "if(!test.yesisav(this))" works very well but when I add "test.displaymess(this)" the app crash. error code :

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapp, PID: 8754
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.mypage}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
        at android.content.ContextWrapper.getTheme(ContextWrapper.java:139)
        at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:227)
        at android.app.AlertDialog$Builder.<init>(AlertDialog.java:469)
        at com.example.myapp.common.connecttest.displaymess(classtesterconnexion.kt:34)
        at com.example.myapp.mypage.onCreate(mypage.kt:21)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:223) 
        at android.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 8754 SIG: 9

when i launch the app it opens and closes immediately, and below the error code displayed in android Studio Thank you

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
admindunet
  • 21
  • 7
  • Remove `: Application` from your `connecttest` file and then you'll see why it fails. As a general rule of thumb, never instantiate classes which inherit `Context` yourself (i.e. `Application`, `Activity`, `Fragment`, `Service`, etc.) – JensV Jan 07 '21 at 19:53
  • Also, there seems to be no reason why the first class even inherits `Application`. Use `Application` classes only when you have a reason to do so. – JensV Jan 07 '21 at 19:55
  • thank you @JensV, now i have this error : Type mismatch: inferred type is connecttest but Context! was expected In line val dialogBuilder = AlertDialog.Builder(this) – admindunet Jan 07 '21 at 20:09
  • Yeah, that's where your error lies. It expects an actual `Context`, the one from `Application` wasn't valid because you instantiated the object by yourself. But you have already have a `Context` readily available in your function parameter, so why not use that? – JensV Jan 07 '21 at 20:11
  • Also see https://stackoverflow.com/questions/3572463/what-is-context-on-android – JensV Jan 07 '21 at 20:13

1 Answers1

0
//Object class
Object connecttest {
     fun yesisav(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val nw = connectivityManager.activeNetwork?: return false
            val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
            return when {
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
                //for other device how are able to connect with Ethernet
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
                //for check internet over Bluetooth
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> true
                else -> false
            }
        } else {
            return connectivityManager.activeNetworkInfo?.isConnected ?: false
        }
    }
  • In your mainActivity , create a function for your alertDialog

fun displayAlertDialog(){
     
       AlertDialog.Builder(this)
       setTitle("AlertDialogExample")
        .setMessage("Do you want to close this application ?")
        .setCancelable(false)
         .setPositiveButton("Proceed", DialogInterface.OnClickListener {
           dialog, id -> finish()
                    })
           .setNegativeButton("Continue", DialogInterface.OnClickListener {
                    dialog, id -> dialog.cancel()
                })
       
        .create()
        .show()
    }
  • then in your activity onCreate , call that function after checking for internet
     if(yesisav(this)){
     fun displayAlertDialog()
    }
Taki
  • 3,290
  • 1
  • 16
  • 41