首页 > 解决方案 > kotlin中的fatel错误检查互联网连接

问题描述

我的应用程序运行良好,没有问题,我使用 AsyncTask 来获取数据 json,一切都很好。我想添加代码以检查我的应用程序中的互联网连接,并将代码放在onCreate主要活动中。

val cm = baseContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = cm.activeNetworkInfo
if (networkInfo != null && networkInfo.isConnected){

    if (networkInfo.type == ConnectivityManager.TYPE_WIFI){

        Toast.makeText(baseContext,"wifi",Toast.LENGTH_SHORT).show()
    }
    if (networkInfo.type == ConnectivityManager.TYPE_MOBILE){

        Toast.makeText(baseContext,"MOBILE",Toast.LENGTH_SHORT).show()
    }

}else {
    Toast.makeText(baseContext,"MOBILE",Toast.LENGTH_SHORT).show()
    this.finish()
}

当我将手机置于飞行计划模式并启动应用程序时,他停止工作。和崩溃。

控制台日志

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: com.iraqairoirt.iraqairports, PID: 10868

主要活动

package com.iraqairoirt.iraqairports

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.os.AsyncTask
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import com.iraqairoirt.iraqairports.BaghdadAirport.ListAdapteArr
import com.iraqairoirt.iraqairports.BaghdadAirport.ListAdapteDep
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import kotlinx.android.synthetic.main.fragment_baghdada_arrivel.*
import kotlinx.android.synthetic.main.fragment_baghdada_dep.*

import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import android.widget.Toast
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.support.design.widget.Snackbar
import com.iraqairoirt.iraqairports.BaghdadAirport.FlightsArrivelBeforBGW
import com.iraqairoirt.iraqairports.BaghdadAirport.FlightsDepBeforBGW


class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        val url = "airport.json"
        Arr().execute(url)


        setSupportActionBar(toolbar)
        val fragmentAdapter = MyPagerAdapter(supportFragmentManager)

        viewpager_main.adapter = fragmentAdapter
        sliding_tabs.setupWithViewPager(viewpager_main)

        val toggle = ActionBarDrawerToggle(
            this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
        )
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        nav_view.setNavigationItemSelectedListener(this)


        val cm = baseContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = cm.activeNetworkInfo
        if (networkInfo != null && networkInfo.isConnected){

            if (networkInfo.type == ConnectivityManager.TYPE_WIFI){

                Toast.makeText(baseContext,"wifi",Toast.LENGTH_SHORT).show()
            }
            if (networkInfo.type == ConnectivityManager.TYPE_MOBILE){

                Toast.makeText(baseContext,"MOBILE",Toast.LENGTH_SHORT).show()
            }

        }else {
            Toast.makeText(baseContext,"MOBILE",Toast.LENGTH_SHORT).show()
            this.finish()
        }

    }


    //    full class for json api
    inner class Arr : AsyncTask<String, String, String>() {

        val progressDialog = AlertDialog.Builder(this@MainActivity)
        val dialogView = layoutInflater.inflate(R.layout.progress_dialog, null)
        val message = dialogView.findViewById<TextView>(R.id.message_id)
        val dialog = progressDialog.create()

        override fun onPreExecute() {
            super.onPreExecute()

            dialog.setMessage("يرجى الانتظار")
            dialog.setCancelable(false)
            dialog.show()


        }

        //        for build connection
        override fun doInBackground(vararg url: String?): String {

            var text: String
            val connection = URL(url[0]).openConnection() as HttpURLConnection

            try {
                connection.connect()
                text = connection.inputStream.use { it.reader().use { reader -> reader.readText() } }


            } finally {

                connection.disconnect()

            }
            return text
        }

        override fun onPostExecute(result: String?) {

            super.onPostExecute(result)
            handleJson(result)

            dialog.dismiss();

        }

        override fun onProgressUpdate(vararg text: String?) {


        }

        @SuppressLint("WrongViewCast")
        private fun handleJson(jsonString: String?) {

            val jsonObj = JSONObject(jsonString)
            val result = jsonObj.getJSONObject("result")
            val response = result.getJSONObject("response")
            val airport = response.getJSONObject("airport")
            val pluginData = airport.getJSONObject("pluginData")
            val schedule = pluginData.getJSONObject("schedule")
            val arrivals = schedule.getJSONObject("arrivals")

//            weather data
            val weather = pluginData.getJSONObject("weather")
            val mater = weather.getString("metar")

//            MaterText.text=mater
//        val data = arrivals.getJSONObject("data")
            val jsonArray = JSONArray(arrivals.get("data").toString())

            val list = ArrayList<FlightShdu>()
            var x = 0
            while (x < jsonArray.length()) {

                val jsonObject = jsonArray.getJSONObject(x)



                list.add(
                    FlightShdu(
                        jsonObject.getJSONObject("flight").getJSONObject("identification").getJSONObject("number").getString(
                            "default"
                        ),
                        jsonObject.getJSONObject("flight").getJSONObject("airline").getString("short"),
                        jsonObject.getJSONObject("flight").getJSONObject("status").getJSONObject("generic").getJSONObject(
                            "status"
                        ).getString("text"),
                        jsonObject.getJSONObject("flight").getJSONObject("airline").getJSONObject("code").getString("icao"),
                        jsonObject.getJSONObject("flight").getJSONObject("time").getJSONObject("scheduled").getString("arrival"),
                        jsonObject.getJSONObject("flight").getJSONObject("airport").getJSONObject("origin").getJSONObject(
                            "code"
                        ).getString("iata"),
                        jsonObject.getJSONObject("flight").getJSONObject("aircraft").getJSONObject("model").getString("code"),
//                    for more information
                        jsonObject.getJSONObject("flight").getJSONObject("time").getJSONObject("real").getString("departure"),
                        jsonObject.getJSONObject("flight").getJSONObject("time").getJSONObject("estimated").getString("arrival"),
//                    jsonObject.getJSONObject("flight").getJSONObject("time").getJSONObject("estimated").getString("arrival"),
                        jsonObject.getJSONObject("flight").getJSONObject("aircraft").getString("registration"),
                        jsonObject.getJSONObject("flight").getJSONObject("status").getJSONObject("generic").getJSONObject(
                            "status"
                        ).getString("diverted"),
                        arrivals.getString("timestamp"),
                        jsonObject.getJSONObject("flight").getJSONObject("status").getString("icon")


                    )
                )


                x++
            }
            list.forEach(::println)

            var adapter = ListAdapteArr(this@MainActivity, list)
            flight_arrivel_list.adapter = adapter


        }

    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        val id = item.itemId

        //noinspection SimplifiableIfStatement

        if (id == R.id.flightarrbeforbgw) {

            val intent = Intent(this, FlightsArrivelBeforBGW::class.java)
            this.startActivity(intent)
            return true
        }

        if (id == R.id.flightdepbefrobgw) {
            val intent = Intent(this, FlightsDepBeforBGW::class.java)
            this.startActivity(intent)
            return true
        }
//
//        if (id == R.id.searchflights) {
//            Toast.makeText(this, "Android Menu is Clicked", Toast.LENGTH_LONG).show()
//            return true
//        }

        return super.onOptionsItemSelected(item)

    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            R.id.nav_camera -> {
                // Handle the camera action
            }
            R.id.nav_gallery -> {

            }
            R.id.nav_slideshow -> {

            }
            R.id.nav_manage -> {

            }
            R.id.nav_share -> {

            }
            R.id.nav_send -> {

            }
        }

        drawer_layout.closeDrawer(GravityCompat.START)
        return true
    }



}

标签: kotlin

解决方案


为了避免在没有互联网连接时出现致命错误和崩溃,我的错误是我应该将 execute() url 放在检查互联网连接的代码中

 val cm = baseContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = cm.activeNetworkInfo
            if (networkInfo != null && networkInfo.isConnected){

                if (networkInfo.type == ConnectivityManager.TYPE_WIFI){


                                        val url = "airport.json"

                    Arr().execute(url)

                }
                if (networkInfo.type == ConnectivityManager.TYPE_MOBILE){


                    val url = "airport.json"
                    Arr().execute(url)
                }

            }else {
   val builder = AlertDialog.Builder(this)
            builder.setTitle("No internet Connection")
            builder.setMessage("Please turn on internet connection to continue")
            builder.setNegativeButton(
                "close"

            ) { dialog, button -> this.finish() }
            val alertDialog = builder.create()
            alertDialog.show()    


            } 

现在我的应用程序运行良好 =)


推荐阅读