Kotlin 设置文本'';未找到结果'';文本编辑

Kotlin 设置文本'';未找到结果'';文本编辑,kotlin,android-asynctask,textedit,Kotlin,Android Asynctask,Textedit,在需要您帮助修改我的代码时,我正试图通过数据json搜索航班号来构建一个包含航班时刻表的应用程序。我正在使用编辑文本、异步任务和自定义列表适配器列表视图。我的应用程序工作正常,但问题是当用户以错误的方式输入航班号时,我得到了致命异常。因为当用户输入正确的航班号时,数据json url他有数据数组,其他方式如果用户输入错误的航班号,数据json url他将在jsonobject和l get致命异常中返回数据json E/AndroidRuntime: FATAL EXCEPTION: main P

在需要您帮助修改我的代码时,我正试图通过数据json搜索航班号来构建一个包含航班时刻表的应用程序。我正在使用编辑文本、异步任务和自定义列表适配器列表视图。我的应用程序工作正常,但问题是当用户以错误的方式输入航班号时,我得到了致命异常。因为当用户输入正确的航班号时,数据json url他有数据数组,其他方式如果用户输入错误的航班号,数据json url他将在
jsonobject
和l get
致命异常中返回数据json

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.iraqairoirt.iraqairports, PID: 5380
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 
 Caused by: org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
    at org.json.JSON.typeMismatch(JSON.java:111)
    at org.json.JSONArray.<init>(JSONArray.java:96)
    at org.json.JSONArray.<init>(JSONArray.java:108)
    at com.iraqairoirt.iraqairports.BaghdadAirport.FlightSearch$Arr.handleJson(FlightSearch.kt:106)
    at com.iraqairoirt.iraqairports.BaghdadAirport.FlightSearch$Arr.onPostExecute(FlightSearch.kt:90)
    at com.iraqairoirt.iraqairports.BaghdadAirport.FlightSearch$Arr.onPostExecute(FlightSearch.kt:58)
    at android.os.AsyncTask.finish(AsyncTask.java:660)
    at android.os.AsyncTask.-wrap1(AsyncTask.java)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 
如果输入错误,则获取数据json对象和致命异常

{
  "result": {
    "request": {},
    "response": {
      "data": null
    }
  }
}
类活动,包括列表适配器

class FlightSearch : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_flight_search)
        flightlistlaout.bringToFront()

    }

    fun getflightsearchresult(view:View){

        val FlightNumber=flightnumbertext.text.toString()
//        val auto=autoCompleteTextView.text.toString()

        if(FlightNumber.trim().length>0) {
            val url = "flight/list.json?query="+FlightNumber+"&fetchBy=flight&page=1&limit=100&token="
            Arr().execute(url)

            Toast.makeText(applicationContext, "Message : ", Toast.LENGTH_SHORT).show()
        }else{
            Toast.makeText(applicationContext, "Please enter some message! ", Toast.LENGTH_SHORT).show()
        }
    }
    inner class Arr : AsyncTask<String, String, String>() {


        override fun onPreExecute() {
            super.onPreExecute()


        }

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

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

            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)


        }

        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 jsonArray = JSONArray(response.get("data").toString())


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

                            val jsonObject = jsonArray.getJSONObject(x)


                            list.add(
                                FlightShdu(
                                    jsonObject.getJSONObject("identification").getJSONObject("number").getString("default"),
                                    jsonObject.getJSONObject("airline").getString("name"),
                                    jsonObject.getJSONObject("status").getJSONObject("generic").getJSONObject("status").getString(
                                        "text"
                                    ),
                                    jsonObject.getJSONObject("airline").getJSONObject("code").getString("icao"),
                                    jsonObject.getJSONObject("time").getJSONObject("scheduled").getString("arrival"),
                                    jsonObject.getJSONObject("airport").getJSONObject("origin").getJSONObject("code").getString(
                                        "iata"


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

                        var adapter = FlightSearchAdpater(this@FlightSearch, list)
                        flightsearchlists.adapter = adapter
        }





        }


    }
    class FlightSearchAdpater (val context: Context, val list: ArrayList<FlightShdu>): BaseAdapter() {


        @SuppressLint("ViewHolder", "NewApi", "WrongViewCast")
        override fun getView(p0: Int, convertView: View?, parent: ViewGroup?): View {

            val view : View = LayoutInflater.from(context).inflate(R.layout.baghdad_arrivel_list,parent,false)

            val list = list[p0]
            val LogoAriline = view.findViewById(R.id.logo_image) as ImageView
            val status = view.findViewById(R.id.ali_id) as AppCompatTextView
            val Airport = view.findViewById(R.id.airportid) as AppCompatTextView
            val code = view.findViewById(R.id.code_id) as AppCompatTextView
            val TimeFlight = view.findViewById(R.id.time_id) as AppCompatTextView
            val checkiflive = view.checkifliveTextId
            view.callsign_id.text=list.Callsign
            view.airline_id.text=list.Airline
            code.text = list.code
            view.ali_id.text=list.Stauts
            status.text= list.Stauts
            TimeFlight.text = getDateTime(list.TimeFlight)

            Picasso.with(context).load(Uri.parse("/data/operators/"+status.text.toString()+"_logo0.png"))
                .error(R.drawable.logo).into(LogoAriline)

            Airport.text= list.Airport
            view.model_id.text=list.Model
            checkiflive.text=list.IfLive




        private fun getDateTime(s: String): String? {
            try {
                val sdf = SimpleDateFormat("EE, MMM d KK:mm a")
                val netDate = Date(s.toLong() * 1000)
                return sdf.format(netDate)
            } catch (e: Exception) {
                return e.toString()

            }
        }

        override fun getItem(p0: Int): Any {
            return list [p0]
        }

        override fun getItemId(p0: Int): Long {
            return p0.toLong()
        }

        override fun getCount(): Int {
            return list.size
        }



    }
class-FlightSearch:AppCompatActivity(){
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity\u flight\u search)
flightlistlaout.bringToFront()
}
趣味getflightsearchresult(视图:视图){
val FlightNumber=flightnumbertext.text.toString()
//val auto=autoCompleteTextView.text.toString()自动完成
如果(FlightNumber.trim().length>0){
val url=“flight/list.json?query=“+FlightNumber+”&fetchBy=flight&page=1&limit=100&token=”
Arr().execute(url)
Toast.makeText(applicationContext,“Message:,Toast.LENGTH\u SHORT.show())
}否则{
Toast.makeText(applicationContext,“请输入一些消息!”,Toast.LENGTH\u SHORT.show()
}
}
内部类Arr:AsyncTask(){
覆盖乐趣onPreExecute(){
super.onPreExecute()
}
//用于构建连接
重写fun doInBackground(varargurl:String?):String{
变量文本:字符串
val connection=URL(URL[0])。openConnection()作为HttpURLConnection
connection.connectTimeout=700
试一试{
connection.connect()
text=connection.inputStream.use{it.reader()。use{reader->reader.readText()}
}最后{
连接断开()
}
返回文本
}
重写onPostExecute(结果:字符串?){
super.onPostExecute(结果)
handleJson(结果)
}
重写进程更新(vararg text:String?){
}
@SuppressLint(“错误视图投射”)
private-fun-handleJson(jsonString:String?){
val jsonObj=JSONObject(jsonString)
val result=jsonObj.getJSONObject(“结果”)
val response=result.getJSONObject(“响应”)
val jsonArray=jsonArray(response.get(“data”).toString())
val list=ArrayList()
变量x=0
而(xclass FlightSearch : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_flight_search)
        flightlistlaout.bringToFront()

    }

    fun getflightsearchresult(view:View){

        val FlightNumber=flightnumbertext.text.toString()
//        val auto=autoCompleteTextView.text.toString()

        if(FlightNumber.trim().length>0) {
            val url = "flight/list.json?query="+FlightNumber+"&fetchBy=flight&page=1&limit=100&token="
            Arr().execute(url)

            Toast.makeText(applicationContext, "Message : ", Toast.LENGTH_SHORT).show()
        }else{
            Toast.makeText(applicationContext, "Please enter some message! ", Toast.LENGTH_SHORT).show()
        }
    }
    inner class Arr : AsyncTask<String, String, String>() {


        override fun onPreExecute() {
            super.onPreExecute()


        }

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

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

            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)


        }

        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 jsonArray = JSONArray(response.get("data").toString())


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

                            val jsonObject = jsonArray.getJSONObject(x)


                            list.add(
                                FlightShdu(
                                    jsonObject.getJSONObject("identification").getJSONObject("number").getString("default"),
                                    jsonObject.getJSONObject("airline").getString("name"),
                                    jsonObject.getJSONObject("status").getJSONObject("generic").getJSONObject("status").getString(
                                        "text"
                                    ),
                                    jsonObject.getJSONObject("airline").getJSONObject("code").getString("icao"),
                                    jsonObject.getJSONObject("time").getJSONObject("scheduled").getString("arrival"),
                                    jsonObject.getJSONObject("airport").getJSONObject("origin").getJSONObject("code").getString(
                                        "iata"


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

                        var adapter = FlightSearchAdpater(this@FlightSearch, list)
                        flightsearchlists.adapter = adapter
        }





        }


    }
    class FlightSearchAdpater (val context: Context, val list: ArrayList<FlightShdu>): BaseAdapter() {


        @SuppressLint("ViewHolder", "NewApi", "WrongViewCast")
        override fun getView(p0: Int, convertView: View?, parent: ViewGroup?): View {

            val view : View = LayoutInflater.from(context).inflate(R.layout.baghdad_arrivel_list,parent,false)

            val list = list[p0]
            val LogoAriline = view.findViewById(R.id.logo_image) as ImageView
            val status = view.findViewById(R.id.ali_id) as AppCompatTextView
            val Airport = view.findViewById(R.id.airportid) as AppCompatTextView
            val code = view.findViewById(R.id.code_id) as AppCompatTextView
            val TimeFlight = view.findViewById(R.id.time_id) as AppCompatTextView
            val checkiflive = view.checkifliveTextId
            view.callsign_id.text=list.Callsign
            view.airline_id.text=list.Airline
            code.text = list.code
            view.ali_id.text=list.Stauts
            status.text= list.Stauts
            TimeFlight.text = getDateTime(list.TimeFlight)

            Picasso.with(context).load(Uri.parse("/data/operators/"+status.text.toString()+"_logo0.png"))
                .error(R.drawable.logo).into(LogoAriline)

            Airport.text= list.Airport
            view.model_id.text=list.Model
            checkiflive.text=list.IfLive




        private fun getDateTime(s: String): String? {
            try {
                val sdf = SimpleDateFormat("EE, MMM d KK:mm a")
                val netDate = Date(s.toLong() * 1000)
                return sdf.format(netDate)
            } catch (e: Exception) {
                return e.toString()

            }
        }

        override fun getItem(p0: Int): Any {
            return list [p0]
        }

        override fun getItemId(p0: Int): Long {
            return p0.toLong()
        }

        override fun getCount(): Int {
            return list.size
        }



    }
  val jsonData  = response.getJSONArray("data")
    if(jsonData.length()!=0)
    {
        // Do your work        
    }
 Object dataVal= response.get("data");
     if (dataValis is JSONArray)
        {
              // Your code                 
        }
     else
      { 
           // null value
      }
 private fun handleJson(jsonString: String?) {

            val jsonObj = JSONObject(jsonString)
            val result = jsonObj.getJSONObject("result")
            val response = result.getJSONObject("response")

            if (jsonObj  is JSONArray) {
                val jsonArray= response.getJSONArray("data")

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

                    val jsonObject = jsonArray.getJSONObject(x)


                    list.add(
                        FlightShdu(
                            jsonObject.getJSONObject("identification").getJSONObject("number").getString("default"),
                            jsonObject.getJSONObject("airline").getString("name"),
                            jsonObject.getJSONObject("status").getJSONObject("generic").getJSONObject("status").getString(
                                "text"
                            ),

                        )
                    )


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

                var adapter = FlightSearchAdpater(this@FlightSearch, list)
                flightsearchlists.adapter = adapter

            }else if(jsonObj is JSONObject){
                val response = result.getJSONObject("response")

                if(response.isNull("data")){
                    Toast.makeText(applicationContext, "Please enter currect flight number", Toast.LENGTH_SHORT).show()
                }

            }



        }