Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 6.34 KB | None | 0 0
  1. package com.example.networking.controller
  2.  
  3. import android.content.Intent
  4. import android.content.res.Configuration
  5. import android.os.AsyncTask
  6. import androidx.appcompat.app.AppCompatActivity
  7. import android.os.Bundle
  8. import android.util.Log
  9. import android.view.Menu
  10. import android.view.MenuItem
  11. import android.view.View
  12. import androidx.recyclerview.widget.GridLayoutManager
  13. import com.example.networking.R
  14. import com.example.networking.adapters.MovieAdapter
  15. import com.example.networking.model.Movie
  16. import kotlinx.android.synthetic.main.activity_main.*
  17. import org.json.JSONArray
  18. import org.json.JSONException
  19. import org.json.JSONObject
  20. import java.lang.ref.WeakReference
  21. import java.net.HttpURLConnection
  22. import java.net.URL
  23.  
  24.  
  25. class MainActivity : AppCompatActivity() {
  26.  
  27.     private val LOG_TAG = "THREADS"
  28.     private val url = "http://www.omdbapi.com/?apikey=a946fa33&s="
  29.  
  30.     private lateinit var movieAdapter: MovieAdapter
  31.     private var myAsyncTask: AsyncTaskHandlerJSON? = null
  32.  
  33.     override fun onCreate(savedInstanceState: Bundle?) {
  34.         super.onCreate(savedInstanceState)
  35.         setContentView(R.layout.activity_main)
  36.  
  37.         setSupportActionBar(toolbar)
  38.  
  39.         myAsyncTask = lastCustomNonConfigurationInstance as? AsyncTaskHandlerJSON
  40.         myAsyncTask?.attachActivity(this)
  41.     }
  42.  
  43.     private fun attachList(curList: ArrayList<Movie>?) {
  44.         if (curList != null) {
  45.             movieAdapter = MovieAdapter(curList, applicationContext) {
  46.                 val intent = Intent(this, MoviesActivity::class.java)
  47.                 intent.putExtra(PICTURE_TAG, it.picture)
  48.                 intent.putExtra(TITLE_TAG, it.title)
  49.                 intent.putExtra(YEAR_TAG, it.year)
  50.                 startActivity(intent)
  51.             }
  52.  
  53.             movieRecyclerView.apply {
  54.                 setHasFixedSize(true)
  55.                 adapter = movieAdapter
  56.                 layoutManager = if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
  57.                     GridLayoutManager(applicationContext, 2)
  58.                 } else {
  59.                     GridLayoutManager(applicationContext, 3)
  60.                 }
  61.             }
  62.         }
  63.     }
  64.  
  65.     private fun downloadUsingAsyncTask(name: String?) {
  66.         myAsyncTask?.activityReference = WeakReference(null)
  67.         myAsyncTask = AsyncTaskHandlerJSON(this).apply {
  68.             execute(url + (name ?: "superman") + "&page=")
  69.             attachActivity(this@MainActivity)
  70.         }
  71.         Log.d(LOG_TAG, "Create MainActivity: " + this@MainActivity.hashCode())
  72.         Log.d(LOG_TAG, "Create AsyncTask: " + myAsyncTask.hashCode())
  73.     }
  74.  
  75.     override fun onRetainCustomNonConfigurationInstance(): Any? {
  76.         return myAsyncTask
  77.     }
  78.  
  79.      private class AsyncTaskHandlerJSON(activity: MainActivity?) : AsyncTask<String, Int, ArrayList<Movie>>() {
  80.  
  81.         var activityReference = WeakReference(activity)
  82.         private var cachedResult: ArrayList<Movie>? = null
  83.  
  84.  
  85.         override fun doInBackground(vararg url: String?): ArrayList<Movie> {
  86.  
  87.             val movieList: ArrayList<Movie> = ArrayList()
  88.  
  89.             for (i in 1..10) {
  90.                 val text: String
  91.                 val connection = URL(url[0] + "$i").openConnection() as HttpURLConnection
  92.                 try {
  93.                     connection.connect()
  94.                     text = connection.inputStream.reader().readText()
  95.                 } finally {
  96.                     connection.disconnect()
  97.                 }
  98.  
  99.                 val jsonArray: JSONArray
  100.                 try {
  101.                     jsonArray = JSONObject(text).getJSONArray("Search")
  102.                 } catch (e: JSONException) {
  103.                     break
  104.                 }
  105.  
  106.                 for (j in 0 until jsonArray.length()) {
  107.                     val jsonObject = jsonArray.getJSONObject(j)
  108.                     movieList.add(
  109.                         Movie(
  110.                             jsonObject.getString("Poster"),
  111.                             jsonObject.getString("Title"),
  112.                             jsonObject.getString("Year")
  113.                         )
  114.                     )
  115.                     publishProgress(j + 10 * (i - 1))
  116.                 }
  117.             }
  118.  
  119.             return movieList
  120.         }
  121.  
  122.         override fun onProgressUpdate(vararg values: Int?) {
  123.             super.onProgressUpdate(*values)
  124.             activityReference.get()?.listProgressBar?.apply {
  125.                 visibility = View.VISIBLE
  126.                 max = 50
  127.                 progress = values[0]!!
  128.             }
  129.         }
  130.        
  131.         fun attachActivity(activity: MainActivity) {
  132.             activityReference = WeakReference(activity)
  133.             cachedResult?.let {
  134.                 activityReference.get()?.setMoviesInUI(it)
  135.                 cachedResult = null
  136.             }
  137.         }
  138.  
  139.         override fun onPostExecute(jsonList: ArrayList<Movie>?) {
  140.             super.onPostExecute(jsonList)
  141.             activityReference.get()?.listProgressBar?.visibility = View.GONE
  142.             activityReference.get()?.setMoviesInUI(jsonList) ?: run {
  143.                 cachedResult = jsonList
  144.             }
  145.         }
  146.     }
  147.  
  148.     private fun setMoviesInUI(curList: ArrayList<Movie>?) {
  149.         if (curList != null) {
  150.             attachList(curList)
  151.         }
  152.         myAsyncTask = null
  153.     }
  154.  
  155.     override fun onDestroy() {
  156.         myAsyncTask?.activityReference = WeakReference(null)
  157.         super.onDestroy()
  158.     }
  159.  
  160.     override fun onCreateOptionsMenu(menu: Menu?): Boolean {
  161.         menuInflater.inflate(R.menu.menu, menu)
  162.  
  163.         val menuItem: MenuItem = menu!!.findItem(R.id.searchToolbar)
  164.         val searchView: androidx.appcompat.widget.SearchView =
  165.             menuItem.actionView as androidx.appcompat.widget.SearchView
  166.  
  167.         searchView.queryHint = "Type here to Search"
  168.         searchView.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
  169.  
  170.             override fun onQueryTextSubmit(curRequest: String?): Boolean {
  171.                 downloadUsingAsyncTask(curRequest)
  172.                 menuItem.collapseActionView()
  173.                 return false
  174.             }
  175.  
  176.             override fun onQueryTextChange(prefix: String?): Boolean {
  177. //                movieAdapter.filter.filter(prefix)
  178.                 return false
  179.             }
  180.         })
  181.  
  182.         return true
  183.     }
  184. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement