I am a beginner Android developer, I wrote this code related to web service, but this program has no output (I am not getting any error). And I'm sure that the API is correct, but it doesn't show anything in the text view.And when the app is running on the device, the internet is on.
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>
CodePudding user response:
When you write a catch block instead of ignoring the exception you get, you should log the exception so you dont miss events occuring in your code. Try something like this in your catch blocks:
Log.e("tag", exception)
And then checkout your Logcat for more info of whats happening to your app.