Advertisement
darryljf

MainActivity.kt

Jul 10th, 2020
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 7.66 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, "")
  57.         Log.d(TAG, url)
  58.         downloadURL(url)
  59.     }
  60.  
  61.     override fun onStart() {
  62.         Log.d(TAG,"onStart called!")
  63.         super.onStart()
  64.     }
  65.  
  66.     override fun onResume() {
  67.         Log.d(TAG,"onResume called!")
  68.         super.onResume()
  69.     }
  70.  
  71.     override fun onPause() {
  72.         Log.d(TAG,"onPause called!")
  73.         super.onPause()
  74.     }
  75.  
  76.     override fun onStop() {
  77.         Log.d(TAG,"onStop called!")
  78.         super.onStop()
  79.     }
  80.  
  81.     override fun onRestart() {
  82.         Log.d(TAG,"onRestart called!")
  83.         super.onRestart()
  84.     }
  85.  
  86.     override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
  87.         Log.d(TAG,"onSaveInstanceState called!")
  88.         super.onSaveInstanceState(outState, outPersistentState)
  89.         outState.putString(STATE_URL, url)
  90.     }
  91.  
  92.     override fun onCreateOptionsMenu(menu: Menu?): Boolean {
  93.         menuInflater.inflate(R.menu.top_menu, menu)
  94.         return true
  95.     }
  96.  
  97.     private fun downloadURL(url:String) {
  98.         downloadData = DownloadData(this, xmlListView)
  99.         downloadData?.execute(url)
  100.     }
  101.  
  102.     override fun onOptionsItemSelected(item: MenuItem): Boolean {
  103.         this.url = when(item.itemId) {
  104.             R.id.breakingNews ->
  105.                 BREAKING_NEWS
  106.             R.id.educationNews ->
  107.                 EDUCATION_NEWS
  108.             R.id.solarSystemNews ->
  109.                 SOLAR_SYSTEM_NEWS
  110.             else ->
  111.                 return super.onOptionsItemSelected(item)
  112.         }
  113.         downloadURL(url)
  114.         return true
  115.     }
  116. }
  117.  
  118. 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
  119.     private val TAG = "DownloadData"
  120.     private var propContext: Context by Delegates.notNull()
  121.     private var propListView: ListView by Delegates.notNull()
  122.     //
  123.     init {
  124.         propContext = context
  125.         propListView = listView
  126.     }
  127.  
  128.     override fun doInBackground(vararg url: String?): String {
  129.         val rssFeed = URL(url[0]).readText()
  130.         if (rssFeed.isEmpty()) {
  131.             Log.e(TAG, "doInBackground: Cant download XML")
  132.         }
  133.         return rssFeed
  134.     }
  135.  
  136.     override fun onPostExecute(result: String?) {
  137.         super.onPostExecute(result)
  138.         Log.d(TAG, "onPostExecute: parameter is $result")
  139.         val parseResults = ParseResults()
  140.         if (result != null) {
  141.             parseResults.parse(result)
  142.         }
  143.         val feedAdapter = FeedAdapter(propContext, R.layout.list_record, parseResults.results)
  144.         propListView.adapter = feedAdapter
  145.     }
  146. }
  147.  
  148.     class ParseResults() {
  149.  
  150.         val results = ArrayList<ResultEntry>()
  151.         // takes the xml data string and converts it i to data
  152.  
  153.         fun parse(xmlData: String): Boolean {
  154.             var status = true
  155.             var inEntry = false
  156.             var textValue = ""
  157.  
  158.             try {
  159.  
  160.                 val factory = XmlPullParserFactory.newInstance()
  161.                 factory.isNamespaceAware = true
  162.                 val xpp = factory.newPullParser()
  163.                 xpp.setInput(xmlData.reader())
  164.                 var eventType = xpp.eventType
  165.                 var currentRecord = ResultEntry()
  166.  
  167.                 while (eventType != XmlPullParser.END_DOCUMENT) {
  168.                     val tagName = xpp.name?.toLowerCase()
  169.  
  170.                     when (eventType) {
  171.                         XmlPullParser.START_TAG -> {
  172.                             if (tagName == "item") {
  173.                                 inEntry = true
  174.                             }
  175.                         }
  176.                         XmlPullParser.TEXT -> textValue = xpp.text
  177.                         XmlPullParser.END_TAG -> {
  178.                             if (inEntry) {
  179.                                 when (tagName) {
  180.                                     "item" -> {
  181.                                         results.add(currentRecord)
  182.                                         inEntry = false
  183.                                         currentRecord = ResultEntry()
  184.                                     }
  185.  
  186.                                     "title" -> currentRecord.title = textValue
  187.                                     "description" -> currentRecord.description = textValue
  188.                                     "link" -> currentRecord.link = textValue
  189.                                 }
  190.                             }
  191.                         }
  192.                     }
  193.                     eventType = xpp.next()
  194.                 }
  195.  
  196.             } catch (e: Exception) {
  197.                 status = false
  198.             }
  199.             return status
  200.         }
  201.     }
  202.  
  203.  
  204. class ViewHolder(v: View) {
  205.     val title: TextView = v.findViewById(R.id.title)
  206.     val description: TextView = v.findViewById(R.id.description)
  207.     val link: TextView = v.findViewById(R.id.link)
  208. }
  209.  
  210. class FeedAdapter(context: Context, private val resource : Int, private val results:
  211. List<ResultEntry>): ArrayAdapter<ResultEntry>(context,resource) {
  212.  
  213.     private val inflater = LayoutInflater.from(context)
  214.  
  215.     override fun getCount(): Int {
  216.         return results.size
  217.     }
  218.  
  219.     override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
  220.         val view:View
  221.         val viewHolder:ViewHolder
  222.         if(convertView == null) {
  223.             view = inflater.inflate(resource,parent,false)
  224.             viewHolder = ViewHolder(view)
  225.             view.tag = viewHolder
  226.         }else{
  227.             // reused the view
  228.             view = convertView
  229.             viewHolder = view.tag as ViewHolder
  230.         }
  231.  
  232.         val currentApp = results[position]
  233.  
  234.         viewHolder.title.text = currentApp.title
  235.         viewHolder.description.text = currentApp.description
  236.         viewHolder.link.text = currentApp.link
  237.  
  238.         return view
  239.     }
  240. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement