Skip to content

Commit

Permalink
Infinite Scrolling Fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
hanupratap committed Jun 10, 2020
1 parent d945771 commit 22a0f0a
Show file tree
Hide file tree
Showing 8 changed files with 176 additions and 37 deletions.
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ dependencies {
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
Expand Down
169 changes: 137 additions & 32 deletions app/src/main/java/com/example/pictures/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,36 @@ package com.example.pictures

import android.app.SearchManager
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar
import androidx.constraintlayout.solver.widgets.WidgetContainer
import androidx.core.view.MenuItemCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.pictures.models.SearchResponse
import com.example.pictures.models.UnsplashPhoto
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_image_preview.*
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.*
import org.w3c.dom.Text
import java.io.IOException
import java.lang.reflect.Type

import kotlin.Exception

external fun decodeURIComponent(encodedURI: String): String

Expand All @@ -42,7 +43,7 @@ class MainActivity : AppCompatActivity() {
lateinit var URL: String
var mainPicList: MutableList<UnsplashPhoto>? = ArrayList()

lateinit var query: String
var query: String = ""
var page: Int = 1

var lastVisibleItem: Int? = null
Expand All @@ -51,13 +52,22 @@ class MainActivity : AppCompatActivity() {

lateinit var adapter: Adapter

fun getQuery(query: String): String {
if (query.equals("")) {
URL =
"https://api.unsplash.com/photos/?" + "page=" + page + "&client_id=" + access_key;
} else {
URL =
"https://api.unsplash.com/search/photos?query=" + query + "&?page=" + page + "&client_id=" + access_key;
}
return URL
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)



adapter = Adapter(mainPicList, this@MainActivity)


Expand All @@ -73,15 +83,15 @@ class MainActivity : AppCompatActivity() {
recyclerView.adapter = adapter


query = "random"
URL =
"https://api.unsplash.com/search/photos?query=" + query + "&?page=" + page + "&client_id=" + access_key;
URL = getQuery("")

CoroutineScope(Main).launch {
myfunc(URL)
}




recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy > 0) {
Expand All @@ -93,16 +103,24 @@ class MainActivity : AppCompatActivity() {
lastVisibleItem = getLastVisibleItem(lastVisiblePositions)
val visibleThreshold = layouManager.spanCount

if (visibleItemCount + visibleThreshold >= totalItemCount) {
if (lastVisiblePositions[1] + visibleThreshold + 2 >= totalItemCount) {
page++
URL =
"https://api.unsplash.com/search/photos?query=" + query + "&client_id=" + access_key + "&page=" + page
URL = getQuery(query)

CoroutineScope(IO).launch {
if (query.equals("")) {
CoroutineScope(IO).launch {

myfunc(URL)
myfunc(URL)

}
} else {
CoroutineScope(IO).launch {

myfuncSearch(URL)

}
}

}

}
Expand All @@ -126,6 +144,8 @@ class MainActivity : AppCompatActivity() {
}




override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.my_menu, menu)

Expand All @@ -140,16 +160,15 @@ class MainActivity : AppCompatActivity() {
if (query1 != null) {
page = 1
query = query1
URL =
"https://api.unsplash.com/search/photos?query=" + query + "&client_id=" + access_key + "&page=" + page
URL = getQuery(query1)
adapter.data?.clear()
}




CoroutineScope(Main).launch {
myfunc(URL)
myfuncSearch(URL)

}

Expand All @@ -163,12 +182,34 @@ class MainActivity : AppCompatActivity() {

}
)

searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
return super.onCreateOptionsMenu(menu)


}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId)
{
R.id.home -> {
if(!query.equals(""))
{
query = ""
CoroutineScope(Main).launch {
adapter.data?.clear()
myfunc(getQuery(""))
}

}



return true
}
else -> return true
}
}

suspend fun myfunc(URL: String) {
withContext(Main) {
Expand All @@ -185,19 +226,86 @@ class MainActivity : AppCompatActivity() {
okClient.newCall(it).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
Toast.makeText(this@MainActivity, "No Result", Toast.LENGTH_LONG).show()
}

override fun onResponse(call: Call, response: Response) {
val body = response?.body?.string()
Log.d("THIS --- ", body)

if(response==null)
{
Toast.makeText(this@MainActivity, "No Result", Toast.LENGTH_LONG).show()

}
// Log.d("THIS --- ", body)

val gson = Gson()

val obj: SearchResponse? =
gson.fromJson(body, SearchResponse::class.java)

val listType: Type =
object : TypeToken<ArrayList<UnsplashPhoto?>?>() {}.type


val obj: List<UnsplashPhoto>
obj =
gson.fromJson(body, listType)
if (obj != null) {
for (i in obj) {
adapter.data?.add(i)
}
}
else
{
Toast.makeText(this@MainActivity, "No Result", Toast.LENGTH_LONG).show()
}

runOnUiThread(
object : Runnable {
override fun run() {
adapter.notifyDataSetChanged()

}
}
)
}
})
}
} catch (e: Exception) {
e.printStackTrace()
}


}

}

suspend fun myfuncSearch(URL: String) {
withContext(Main) {


var request: Request = URL?.let {
Request.Builder()
.url(it)
.build()
}

try {
request?.let {
okClient.newCall(it).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}

override fun onResponse(call: Call, response: Response) {
val body = response?.body?.string()
Log.d("THIS --- ", body)

val gson = Gson()


val obj: SearchResponse
obj =
gson.fromJson(body, SearchResponse::class.java)
if (obj?.results != null) {
for (i in obj?.results) {
adapter.data?.add(i)
Expand All @@ -208,6 +316,10 @@ class MainActivity : AppCompatActivity() {







runOnUiThread(
object : Runnable {
override fun run() {
Expand All @@ -226,19 +338,12 @@ class MainActivity : AppCompatActivity() {
}
})
}
}
catch (e:Exception)
{
} catch (e: Exception) {
e.printStackTrace()
}




}


}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.example.pictures.models

class ListUnSplashPics ( val pics:List<UnsplashPhoto>) {
}

10 changes: 10 additions & 0 deletions app/src/main/res/drawable/ic_baseline_home_24.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M10,20v-6h4v6h5v-8h3L12,3 2,12h3v8z"/>
</vector>
10 changes: 10 additions & 0 deletions app/src/main/res/drawable/ic_baseline_search_24.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zM9.5,14C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z"/>
</vector>
4 changes: 1 addition & 3 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/colorPrimary"
>


android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
Expand Down
12 changes: 10 additions & 2 deletions app/src/main/res/menu/my_menu.xml
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
android:id="@+id/home"

android:icon="@drawable/ic_baseline_home_24"
android:title="Home"
app:showAsAction="always" />

<item
android:id="@+id/action_search"

android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
android:title="Search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:title="Search"/>
app:showAsAction="always|collapseActionView" />
</menu>
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@
<string name="unsplash_access_key">Z74lgJUMfOoTDEVIW-nVuQ12m3vjWALKTHUeC8tC1Ho</string>
<string name="unsplash_secret_key">nco37vbzRQwWFe0II8kLCWoYOgdTD3QWyVzHaQ-8uI0</string>



</resources>

0 comments on commit 22a0f0a

Please sign in to comment.