I have a fragment_X (class + layout) where i would like to read the online Json file, (you also able to read txt file), and show the content to TextView.
==> NOTE: give application have a right to access internet in Manifest.
class Fragment_X: Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_X, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if(isNetworkAvailable()) {
val myRunnable = Conn(mHandler)
val myThread = Thread(myRunnable)
myThread.start()
}
}
// create a handle to add message
private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(inputMessage: Message) { if (inputMessage.what == 0) {
textView.text = inputMessage.obj.toString() }
} }
// first, check if network is available.
private fun isNetworkAvailable(): Boolean { val cm = requireActivity().getSystemService(
Context.CONNECTIVITY_SERVICE
) as ConnectivityManager
return cm.activeNetworkInfo?.isConnected == true
}
//create a worker with a Handler as parameter
class Conn(mHand: Handler): Runnable {
val myHandler = mHand
override fun run() {
var content = StringBuilder()
try {
// declare URL to text file, create a connection to it and put into stream.
val myUrl = URL("http:.........json") // or URL to txt file
val urlConnection = myUrl.openConnection() as HttpURLConnection
val inputStream = urlConnection.inputStream
// get text from stream, convert to string and send to main thread.
val allText = inputStream.bufferedReader().use { it.readText() }
content.append(allText)
val str = content.toString()
val msg = myHandler.obtainMessage()
msg.what = 0
msg.obj = str
myHandler.sendMessage(msg)
} catch (e: Exception) {
Log.d("Error", e.toString())
}
}
}
}