我是一个初学者的Android开发人员,我写了这个代码有关的网络服务,但这个程序没有输出(我没有得到任何错误)。我敢肯定,API是正确的,但它没有显示任何文本视图。当应用程序在设备上运行,互联网是开着的。
维护活动:
class MainActivity : AppCompatActivity() {
lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
binding.button.setOnClickListener(){
get()
}
}
fun get() {
var cityname = binding.editTextTextPersonName.text.toString()
val endpoint = "http://api.weatherapi.com/v1/current.json? ****** &q=ya&aqi=no"
myAsyncTask().execute(endpoint)
}
inner class myAsyncTask : AsyncTask<String, String, String>() {
override fun doInBackground(vararg params: String?): String {
try {
val url = URL(params[0])
val urlconnect=url.openConnection() as HttpURLConnection
urlconnect.connectTimeout=100000
val instring=convertsteamtoString(urlconnect.inputStream)
publishProgress(instring)
}catch (ex:Exception){}
return ""
}
override fun onProgressUpdate(vararg values: String) {
try {
val json =JSONObject(values[0])
var current=json.getJSONObject("current")
var temp_c =current.getString("temp_c")
binding.textviewtemperature.text=temp_c
}catch (ex:Exception){}
}
fun convertsteamtoString(inputStream :InputStream):String{
val bufferReader =BufferedReader(InputStreamReader(inputStream))
var line:String
var allString :String =""
try {
do{
line = bufferReader.readLine()
allString += line
}while (line != null)
}catch (ex:Exception){}
return allString
}
}
}
机器人清单:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.webservice">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WebService"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
1条答案
按热度按时间7d7tgy0s1#
当你编写一个catch块而不是忽略你得到的异常时,你应该记录异常,这样你就不会错过代码中发生的事件。在你的catch块中尝试这样做:
然后检查你的Logcat,了解你的应用程序发生了什么。