Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.networking.controller
- import android.content.Intent
- import android.content.res.Configuration
- import android.os.AsyncTask
- import androidx.appcompat.app.AppCompatActivity
- import android.os.Bundle
- import android.util.Log
- import android.view.Menu
- import android.view.MenuItem
- import android.view.View
- import androidx.recyclerview.widget.GridLayoutManager
- import com.example.networking.R
- import com.example.networking.adapters.MovieAdapter
- import com.example.networking.model.Movie
- import kotlinx.android.synthetic.main.activity_main.*
- import org.json.JSONArray
- import org.json.JSONException
- import org.json.JSONObject
- import java.lang.ref.WeakReference
- import java.net.HttpURLConnection
- import java.net.URL
- class MainActivity : AppCompatActivity() {
- private val LOG_TAG = "THREADS"
- private val url = "http://www.omdbapi.com/?apikey=a946fa33&s="
- private lateinit var movieAdapter: MovieAdapter
- private var myAsyncTask: AsyncTaskHandlerJSON? = null
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- setSupportActionBar(toolbar)
- myAsyncTask = lastCustomNonConfigurationInstance as? AsyncTaskHandlerJSON
- myAsyncTask?.attachActivity(this)
- }
- private fun attachList(curList: ArrayList<Movie>?) {
- if (curList != null) {
- movieAdapter = MovieAdapter(curList, applicationContext) {
- val intent = Intent(this, MoviesActivity::class.java)
- intent.putExtra(PICTURE_TAG, it.picture)
- intent.putExtra(TITLE_TAG, it.title)
- intent.putExtra(YEAR_TAG, it.year)
- startActivity(intent)
- }
- movieRecyclerView.apply {
- setHasFixedSize(true)
- adapter = movieAdapter
- layoutManager = if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
- GridLayoutManager(applicationContext, 2)
- } else {
- GridLayoutManager(applicationContext, 3)
- }
- }
- }
- }
- private fun downloadUsingAsyncTask(name: String?) {
- myAsyncTask?.activityReference = WeakReference(null)
- myAsyncTask = AsyncTaskHandlerJSON(this).apply {
- execute(url + (name ?: "superman") + "&page=")
- attachActivity(this@MainActivity)
- }
- Log.d(LOG_TAG, "Create MainActivity: " + this@MainActivity.hashCode())
- Log.d(LOG_TAG, "Create AsyncTask: " + myAsyncTask.hashCode())
- }
- override fun onRetainCustomNonConfigurationInstance(): Any? {
- return myAsyncTask
- }
- private class AsyncTaskHandlerJSON(activity: MainActivity?) : AsyncTask<String, Int, ArrayList<Movie>>() {
- var activityReference = WeakReference(activity)
- private var cachedResult: ArrayList<Movie>? = null
- override fun doInBackground(vararg url: String?): ArrayList<Movie> {
- val movieList: ArrayList<Movie> = ArrayList()
- for (i in 1..10) {
- val text: String
- val connection = URL(url[0] + "$i").openConnection() as HttpURLConnection
- try {
- connection.connect()
- text = connection.inputStream.reader().readText()
- } finally {
- connection.disconnect()
- }
- val jsonArray: JSONArray
- try {
- jsonArray = JSONObject(text).getJSONArray("Search")
- } catch (e: JSONException) {
- break
- }
- for (j in 0 until jsonArray.length()) {
- val jsonObject = jsonArray.getJSONObject(j)
- movieList.add(
- Movie(
- jsonObject.getString("Poster"),
- jsonObject.getString("Title"),
- jsonObject.getString("Year")
- )
- )
- publishProgress(j + 10 * (i - 1))
- }
- }
- return movieList
- }
- override fun onProgressUpdate(vararg values: Int?) {
- super.onProgressUpdate(*values)
- activityReference.get()?.listProgressBar?.apply {
- visibility = View.VISIBLE
- max = 50
- progress = values[0]!!
- }
- }
- fun attachActivity(activity: MainActivity) {
- activityReference = WeakReference(activity)
- cachedResult?.let {
- activityReference.get()?.setMoviesInUI(it)
- cachedResult = null
- }
- }
- override fun onPostExecute(jsonList: ArrayList<Movie>?) {
- super.onPostExecute(jsonList)
- activityReference.get()?.listProgressBar?.visibility = View.GONE
- activityReference.get()?.setMoviesInUI(jsonList) ?: run {
- cachedResult = jsonList
- }
- }
- }
- private fun setMoviesInUI(curList: ArrayList<Movie>?) {
- if (curList != null) {
- attachList(curList)
- }
- myAsyncTask = null
- }
- override fun onDestroy() {
- myAsyncTask?.activityReference = WeakReference(null)
- super.onDestroy()
- }
- override fun onCreateOptionsMenu(menu: Menu?): Boolean {
- menuInflater.inflate(R.menu.menu, menu)
- val menuItem: MenuItem = menu!!.findItem(R.id.searchToolbar)
- val searchView: androidx.appcompat.widget.SearchView =
- menuItem.actionView as androidx.appcompat.widget.SearchView
- searchView.queryHint = "Type here to Search"
- searchView.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
- override fun onQueryTextSubmit(curRequest: String?): Boolean {
- downloadUsingAsyncTask(curRequest)
- menuItem.collapseActionView()
- return false
- }
- override fun onQueryTextChange(prefix: String?): Boolean {
- // movieAdapter.filter.filter(prefix)
- return false
- }
- })
- return true
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement