class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// the function code crushemT
crushemT(this)
setContent {
MyConstraintLayoutTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MyScreen()
}
}
}
}
}
fun crushemT(context: Context) {
val url = URL("https://vnexpress.net/rss/the-gioi.rss")
val conn: URLConnection = url.openConnection() as HttpURLConnection
conn.connect()
val inputStream: InputStream = conn.getInputStream()
if (HttpURLConnection.HTTP_OK == 200) {
print("Success")
} else print("Fail")
try {
val factory = XmlPullParserFactory.newInstance()
factory.isNamespaceAware = false
val xpp = factory.newPullParser()
// setting the namespaces feature to false
xpp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
xpp.setInput(inputStream, "UTF-8")
var eventType = xpp.eventType
while (eventType != XmlPullParser.END_DOCUMENT) {
when (eventType) {
XmlPullParser.START_DOCUMENT -> {
println("Start document")
}
XmlPullParser.START_TAG -> {
println("Start tag " + xpp.name)
}
XmlPullParser.END_TAG -> {
println("End tag " + xpp.name)
}
XmlPullParser.TEXT -> {
println("Text " + xpp.text)
}
}
eventType = xpp.next()
}
println("End document")
} catch (e: XmlPullParserException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
}
The code when run show errors
FATAL EXCEPTION: main Process: com.example.myconstraintlayout, PID: 16389 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myconstraintlayout/com.example.myconstraintlayout.MainActivity}: android.os.NetworkOnMainThreadException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3645) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3782) with tag AndroidRuntime
I asked studio bot in android studio it said
The error message is saying that you are trying to access the network on the main thread. This is not allowed in Android, because it can cause the application to become unresponsive.
To fix this error, you need to move your network code to a background thread. You can do this by using the AsyncTask class.
And chatgpt suggeted me using AsyncTask but This class was deprecated in API level 30.
Can someone help me about this, i am a newbie, thanks