我是一个新手Android开发人员,我写了这段与web服务相关的代码,但是这个程序没有输出(我没有得到任何错误)。我确信API是正确的,但它在文本视图中没有显示任何东西。当应用程序在设备上运行时,互联网是打开的。
mainActiviy:
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
}
}
}
androidmanifest:
<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>
当你编写catch块而不是忽略你得到的异常时,你应该记录异常,这样你就不会错过代码中发生的事件。在catch块中尝试这样做:
Log.e("tag", exception)
然后检查你的Logcat更多的信息发生了什么,你的应用程序