Advertisement
darryljf

MainActivity.kt

Jul 8th, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 7.60 KB | None | 0 0
  1. package com.example.top10
  2.  
  3. import android.content.Context
  4. import android.os.AsyncTask
  5. import androidx.appcompat.app.AppCompatActivity
  6. import android.os.Bundle
  7. import android.os.PersistableBundle
  8. import android.util.Log
  9. import android.view.*
  10. import android.widget.ArrayAdapter
  11. import android.widget.ListView
  12. import android.widget.TextView
  13. import kotlinx.android.synthetic.main.activity_main.*
  14. import org.xmlpull.v1.XmlPullParser
  15. import org.xmlpull.v1.XmlPullParserFactory
  16. import java.lang.Exception
  17. import java.net.URL
  18. import kotlin.properties.Delegates
  19.  
  20. private const val TAG = "MainActivity"
  21.  
  22. class ResultEntry() {
  23.     var title: String = ""
  24.     var description: String = ""
  25.     var link: String = ""
  26. }
  27.  
  28. private const val BREAKING_NEWS = "https://www.nasa.gov/rss/dyn/breaking_news.rss"
  29. private const val EDUCATION_NEWS = "https://www.nasa.gov/rss/dyn/educationnews.rss"
  30. private const val SOLAR_SYSTEM_NEWS = "https://www.nasa.gov/rss/dyn/solar_system.rss"
  31. private const val STATE_URL = ""
  32.  
  33. class MainActivity : AppCompatActivity() {
  34.  
  35.     private var url = BREAKING_NEWS
  36.     private var downloadData: DownloadData? = null
  37.  
  38.     override fun onCreate(savedInstanceState: Bundle?) {
  39.         Log.d(TAG,"onCreate called!")
  40.         super.onCreate(savedInstanceState)
  41.         setContentView(R.layout.activity_main)
  42.         if(savedInstanceState != null) {
  43.             url = savedInstanceState.getString(STATE_URL, url)
  44.         }
  45.         downloadURL(url)
  46.     }
  47.  
  48.     override fun onDestroy() {
  49.         Log.d(TAG,"onDestroy called!")
  50.         super.onDestroy()
  51.     }
  52.  
  53.     override fun onRestoreInstanceState(savedInstanceState: Bundle) {
  54.         Log.d(TAG,"onRestoreInstanceState called!")
  55.         super.onRestoreInstanceState(savedInstanceState)
  56.         url = savedInstanceState.getString(STATE_URL,url)
  57.     }
  58.  
  59.     override fun onStart() {
  60.         Log.d(TAG,"onStart called!")
  61.         super.onStart()
  62.     }
  63.  
  64.     override fun onResume() {
  65.         Log.d(TAG,"onResume called!")
  66.         super.onResume()
  67.     }
  68.  
  69.     override fun onPause() {
  70.         Log.d(TAG,"onPause called!")
  71.         super.onPause()
  72.     }
  73.  
  74.     override fun onStop() {
  75.         Log.d(TAG,"onStop called!")
  76.         super.onStop()
  77.     }
  78.  
  79.     override fun onRestart() {
  80.         Log.d(TAG,"onRestart called!")
  81.         super.onRestart()
  82.     }
  83.  
  84.     override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
  85.         Log.d(TAG,"onSaveInstanceState called!")
  86.         super.onSaveInstanceState(outState, outPersistentState)
  87.         outState?.putString(STATE_URL, url)
  88.     }
  89.  
  90.     override fun onCreateOptionsMenu(menu: Menu?): Boolean {
  91.         menuInflater.inflate(R.menu.top_menu, menu)
  92.         return true
  93.     }
  94.  
  95.     private fun downloadURL(url:String) {
  96.         downloadData = DownloadData(this, xmlListView)
  97.         downloadData?.execute(url)
  98.     }
  99.  
  100.     override fun onOptionsItemSelected(item: MenuItem): Boolean {
  101.         this.url = when(item.itemId) {
  102.             R.id.breakingNews ->
  103.                 BREAKING_NEWS
  104.             R.id.educationNews ->
  105.                 EDUCATION_NEWS
  106.             R.id.solarSystemNews ->
  107.                 SOLAR_SYSTEM_NEWS
  108.             else ->
  109.                 return super.onOptionsItemSelected(item)
  110.         }
  111.         downloadURL(url)
  112.         return true
  113.     }
  114. }
  115.  
  116. class DownloadData(context: Context,listView: ListView) : AsyncTask<String, Void, String>() { // handles the downloading of xml data. Extends AsyncTask class. Enables data to be fetched asynchronously
  117.     private val TAG = "DownloadData"
  118.     private var propContext: Context by Delegates.notNull()
  119.     private var propListView: ListView by Delegates.notNull()
  120.     //
  121.     init {
  122.         propContext = context
  123.         propListView = listView
  124.     }
  125.  
  126.     override fun doInBackground(vararg url: String?): String {
  127.         val rssFeed = URL(url[0]).readText()
  128.         if (rssFeed.isEmpty()) {
  129.             Log.e(TAG, "doInBackground: Cant download XML")
  130.         }
  131.         return rssFeed
  132.     }
  133.  
  134.     override fun onPostExecute(result: String?) {
  135.         super.onPostExecute(result)
  136.         Log.d(TAG, "onPostExecute: parameter is $result")
  137.         val parseResults = ParseResults()
  138.         if (result != null) {
  139.             parseResults.parse(result)
  140.         }
  141.         val feedAdapter = FeedAdapter(propContext, R.layout.list_record, parseResults.results)
  142.         propListView.adapter = feedAdapter
  143.     }
  144. }
  145.  
  146.     class ParseResults() {
  147.  
  148.         val results = ArrayList<ResultEntry>()
  149.         // takes the xml data string and converts it i to data
  150.  
  151.         fun parse(xmlData: String): Boolean {
  152.             var status = true
  153.             var inEntry = false
  154.             var textValue = ""
  155.  
  156.             try {
  157.  
  158.                 val factory = XmlPullParserFactory.newInstance()
  159.                 factory.isNamespaceAware = true
  160.                 val xpp = factory.newPullParser()
  161.                 xpp.setInput(xmlData.reader())
  162.                 var eventType = xpp.eventType
  163.                 var currentRecord = ResultEntry()
  164.  
  165.                 while (eventType != XmlPullParser.END_DOCUMENT) {
  166.                     val tagName = xpp.name?.toLowerCase()
  167.  
  168.                     when (eventType) {
  169.                         XmlPullParser.START_TAG -> {
  170.                             if (tagName == "item") {
  171.                                 inEntry = true
  172.                             }
  173.                         }
  174.                         XmlPullParser.TEXT -> textValue = xpp.text
  175.                         XmlPullParser.END_TAG -> {
  176.                             if (inEntry) {
  177.                                 when (tagName) {
  178.                                     "item" -> {
  179.                                         results.add(currentRecord)
  180.                                         inEntry = false
  181.                                         currentRecord = ResultEntry()
  182.                                     }
  183.  
  184.                                     "title" -> currentRecord.title = textValue
  185.                                     "description" -> currentRecord.description = textValue
  186.                                     "link" -> currentRecord.link = textValue
  187.                                 }
  188.                             }
  189.                         }
  190.                     }
  191.                     eventType = xpp.next()
  192.                 }
  193.  
  194.             } catch (e: Exception) {
  195.                 status = false
  196.             }
  197.             return status
  198.         }
  199.     }
  200.  
  201.  
  202. class ViewHolder(v: View) {
  203.     val title: TextView = v.findViewById(R.id.title)
  204.     val description: TextView = v.findViewById(R.id.description)
  205.     val link: TextView = v.findViewById(R.id.link)
  206. }
  207.  
  208. class FeedAdapter(context: Context, private val resource : Int, private val results:
  209. List<ResultEntry>): ArrayAdapter<ResultEntry>(context,resource) {
  210.  
  211.     private val inflater = LayoutInflater.from(context)
  212.  
  213.     override fun getCount(): Int {
  214.         return results.size
  215.     }
  216.  
  217.     override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
  218.         val view:View
  219.         val viewHolder:ViewHolder
  220.         if(convertView == null) {
  221.             view = inflater.inflate(resource,parent,false)
  222.             viewHolder = ViewHolder(view)
  223.             view.tag = viewHolder
  224.         }else{
  225.             // reused the view
  226.             view = convertView
  227.             viewHolder = view.tag as ViewHolder
  228.         }
  229.  
  230.         val currentApp = results[position]
  231.  
  232.         viewHolder.title.text = currentApp.title
  233.         viewHolder.description.text = currentApp.description
  234.         viewHolder.link.text = currentApp.link
  235.  
  236.         return view
  237.     }
  238. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement