Combine two setcontentview in Kotlin - kotlin

For the DoaHome.kt i want to put two setcontentview. The first one is setContentView(R.layout.cover_home_doa) for the navigation drawer. The other one is setContentView(binding.root) for the expandable list.
This the code of DoaHome.kt
package com.example.senangumrah
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.example.senangumrah.databinding.ActivityDoaHomeBinding
import kotlinx.android.synthetic.main.activity_persediaan_home.*
import kotlinx.android.synthetic.main.cover_home_amalan_selepas.*
import kotlinx.android.synthetic.main.cover_home_amalan_selepas.navigationView
import kotlinx.android.synthetic.main.cover_home_doa.*
import kotlinx.android.synthetic.main.cover_home_persediaan.*
import kotlinx.android.synthetic.main.layout_side_menu.*
class DoaHome : AppCompatActivity(), View.OnClickListener {
private lateinit var binding: ActivityDoaHomeBinding
private lateinit var listViewAdapter: ExpandableListViewAdapter
private lateinit var chapterList: List<String>
private lateinit var topicList: HashMap<String, List<String>>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDoaHomeBinding.inflate(layoutInflater)
setContentView(R.layout.cover_home_doa)
setContentView(binding.root)
onSetNavigationDrawerEvents()
showList()
listViewAdapter = ExpandableListViewAdapter( context = this, chapterList, topicList)
binding.eListView.setAdapter(listViewAdapter)
val btnback : ImageView = findViewById(R.id.buttonback)
btnback.setOnClickListener {
finish()
}
}
private fun showList() {
chapterList = ArrayList()
topicList = HashMap()
(chapterList as ArrayList<String>).add("Sebelum Berlepas")
(chapterList as ArrayList<String>).add("Setelah Sampai")
(chapterList as ArrayList<String>).add("Sebelum Masuk Mekah")
(chapterList as ArrayList<String>).add("Ketika di Kaabah")
(chapterList as ArrayList<String>).add("Ketika Tawaf")
(chapterList as ArrayList<String>).add("Keluar dari Mekah")
(chapterList as ArrayList<String>).add("Sebelum Masuk Madinah")
(chapterList as ArrayList<String>).add("Ketika di Masjid Nabawi")
(chapterList as ArrayList<String>).add("Ketika di Raudhah")
(chapterList as ArrayList<String>).add("Keluar dari Madinah")
val topic1 : MutableList<String> = ArrayList()
topic1.add("Doa Naik Kenderaan")
topic1.add("Doa Keselamatan Diri dan Harta")
topic1.add("Doa Dipermudahkan Urusan")
val topic2 : MutableList<String> = ArrayList()
topic2.add("Topic 1")
topic2.add("Topic 2")
topic2.add("Topic 3")
val topic3 : MutableList<String> = ArrayList()
topic3.add("Topic 1")
topic3.add("Topic 2")
topic3.add("Topic 3")
val topic4 : MutableList<String> = ArrayList()
topic4.add("Topic 1")
topic4.add("Topic 2")
topic4.add("Topic 3")
val topic5 : MutableList<String> = ArrayList()
topic5.add("Topic 1")
topic5.add("Topic 2")
topic5.add("Topic 3")
val topic6 : MutableList<String> = ArrayList()
topic6.add("Topic 1")
topic6.add("Topic 2")
topic6.add("Topic 3")
val topic7 : MutableList<String> = ArrayList()
topic7.add("Topic 1")
topic7.add("Topic 2")
topic7.add("Topic 3")
val topic8 : MutableList<String> = ArrayList()
topic8.add("Topic 1")
topic8.add("Topic 2")
topic8.add("Topic 3")
val topic9 : MutableList<String> = ArrayList()
topic9.add("Topic 1")
topic9.add("Topic 2")
topic9.add("Topic 3")
val topic10 : MutableList<String> = ArrayList()
topic10.add("Topic 1")
topic10.add("Topic 2")
topic10.add("Topic 3")
topicList[chapterList[0]] = topic1
topicList[chapterList[1]] = topic2
topicList[chapterList[2]] = topic3
topicList[chapterList[3]] = topic4
topicList[chapterList[4]] = topic5
topicList[chapterList[5]] = topic6
topicList[chapterList[6]] = topic7
topicList[chapterList[7]] = topic8
topicList[chapterList[8]] = topic9
topicList[chapterList[9]] = topic10
}
private fun onSetNavigationDrawerEvents() {
navigation_button.setOnClickListener(this)
ll_First.setOnClickListener(this)
ll_Second.setOnClickListener(this)
ll_Third.setOnClickListener(this)
ll_Fourth.setOnClickListener(this)
ll_Fifth.setOnClickListener(this)
ll_Sixth.setOnClickListener(this)
close.setOnClickListener(this)
}
override fun onClick(v: View) {
when (v.id) {
R.id.navigation_button -> {
doaDrawerLayout.openDrawer(navigationView, true)
}
R.id.ll_First -> {
val button = findViewById<TextView>(R.id.menu_persediaan)
button.setOnClickListener{
val intent = Intent(this, PersediaanHome::class.java)
startActivity(intent)
doaDrawerLayout.closeDrawer(navigationView, true)
}
}
R.id.ll_Second -> {
val button = findViewById<TextView>(R.id.menu_kursus)
button.setOnClickListener{
val intent = Intent(this, KursusHome::class.java)
startActivity(intent)
doaDrawerLayout.closeDrawer(navigationView, true)
}
}
R.id.ll_Third -> {
val button = findViewById<TextView>(R.id.menu_amalansemasa)
button.setOnClickListener{
val intent = Intent(this, AmalanSemasaHome::class.java)
startActivity(intent)
doaDrawerLayout.closeDrawer(navigationView, true)
}
}
R.id.ll_Fourth -> {
val button = findViewById<TextView>(R.id.menu_doa)
button.setOnClickListener{
val intent = Intent(this, TempatZiarahHome::class.java)
startActivity(intent)
doaDrawerLayout.closeDrawer(navigationView, true)
}
}
R.id.ll_Fifth -> {
val button = findViewById<TextView>(R.id.menu_tempat)
button.setOnClickListener{
val intent = Intent(this, TempatZiarahHome::class.java)
startActivity(intent)
doaDrawerLayout.closeDrawer(navigationView, true)
}
}
R.id.ll_Sixth -> {
val button = findViewById<TextView>(R.id.menu_amalanselepas)
button.setOnClickListener{
val intent = Intent(this, AmalanSelepasHome::class.java)
startActivity(intent)
doaDrawerLayout.closeDrawer(navigationView, true)
}
}
R.id.close -> {
showToast("Amalan Selepas Umrah Home")
doaDrawerLayout.closeDrawer(navigationView, true)
}
else -> {
showToast("Amalan Selepas Umrah Home")
doaDrawerLayout.closeDrawer(navigationView, true)
}
}
}
private fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
override fun onBackPressed() {
if ( doaDrawerLayout.isDrawerOpen(navigationView)) {
doaDrawerLayout.closeDrawer(navigationView, true)
} else {
super.onBackPressed()
}
}
override fun onDestroy() {
super.onDestroy()
}
}
when i put the two setcontentview...my interface is blank..the content not appear and the navigation drawer also does not function..then after that the application suddenly stop responding.

setContentView sets the one-and-only root view of the Activity, so it only makes sense to call it once. If you want to use separate layout files for your drawer and your other content, you can create a top level layout file that defines the layout in it's entirety, and you can use <include/> elements to include other layout files in this top-level layout.

Related

Type mismatch: inferred type is CategoryQuran but MainAdapter.onSelectData

i am just trying to code for Get API, but when i write some code for that. it seems error, i took a few hours but i not get the point, can you guys help me?
this is the Activity (ActivityQuran)
class CategoryQuran : AppCompatActivity() {
var mainAdapter: MainAdapter? = null
var mProgressBar: ProgressDialog? = null
var modelMain: MutableList<ModelMain> = ArrayList()
private lateinit var adapter: MainAdapter
private lateinit var postArrayList: ArrayList<MainAdapter>
private lateinit var progressDialog: ProgressDialog
private val TAG = "MAIN_TAG"
private var isSearch = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail_artikel)
//setup progress dialog
progressDialog = ProgressDialog (this)
progressDialog.setTitle("Mohon Tunggu")
mProgressBar = ProgressDialog(this)
mProgressBar!!.setTitle("Mohon Tunggu")
mProgressBar!!.setCancelable(false)
mProgressBar!!.setMessage("Sedang menampilkan data...")
llAbout.setOnClickListener {
startActivity(Intent(this#CategoryQuran, AboutActivity::class.java)) }
llPP.setOnClickListener {
startActivity(Intent(this#CategoryQuran, PrivacyPolicyActivity::class.java)) }
llDisclaimer.setOnClickListener {
startActivity(Intent(this#CategoryQuran, DisclaimerActivity::class.java)) }
rvListArticles.setHasFixedSize(true)
rvListArticles.setLayoutManager(LinearLayoutManager(this))
//get data
listArticle
//search
searchBtn.setOnClickListener {
}
}
private val listArticle: Unit
private get() {
mProgressBar!!.show()
AndroidNetworking.get(BloggerApi.ListPost)
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(object : JSONObjectRequestListener {
override fun onResponse(response: JSONObject) {
try {
mProgressBar!!.dismiss()
val playerArray = response.getJSONArray("items")
for (i in 0 until playerArray.length()) {
val jsonObject1 = playerArray.getJSONObject(i)
val dataApi = ModelMain()
dataApi.title = jsonObject1.getString("title")
dataApi.content = jsonObject1.getString("content")
dataApi.labels = jsonObject1.getString("labels")
dataApi.url = jsonObject1.getString("url")
val datePost = jsonObject1.getString("published")
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
val outputFormat = SimpleDateFormat("dd-MM-yyyy")
val date = inputFormat.parse(datePost)
val datePostConvert = outputFormat.format(date)
dataApi.published = datePostConvert
val jsonObject2 = jsonObject1.getJSONObject("author")
val authorPost = jsonObject2.getString("displayName")
dataApi.author = authorPost
val jsonObject3 = jsonObject2.getJSONObject("image")
val authorImage = jsonObject3.getString("url")
dataApi.authorImage = Uri.parse("http:$authorImage").toString()
modelMain.add(dataApi)
showListArticle()
}
} catch (e: JSONException) {
e.printStackTrace()
Toast.makeText(this#CategoryQuran,
"Gagal menampilkan data!", Toast.LENGTH_SHORT).show()
} catch (e: ParseException) {
e.printStackTrace()
Toast.makeText(this#CategoryQuran,
"Gagal menampilkan data!", Toast.LENGTH_SHORT).show()
}
}
override fun onError(anError: ANError) {
mProgressBar!!.dismiss()
Toast.makeText(this#CategoryQuran,
"Tidak ada jaringan internet!", Toast.LENGTH_SHORT).show()
}
})
}
private fun showListArticle(){
mainAdapter = MainAdapter(this#CategoryQuran, modelMain, this )
rvListArticles!!.adapter = mainAdapter
}
private fun searchPosts(query: String) {
mainAdapter = MainAdapter(this#CategoryQuran, modelMain, this)
rvListArticles!!.adapter = mainAdapter
}
override fun onSelected(modelMain: ModelMain) {
val intent = Intent(this#CategoryQuran, DetailArtikelActivity::class.java)
intent.putExtra("detailArtikel", modelMain)
startActivity(intent)
}
}
i got error in 'this'
private fun showListArticle(){
mainAdapter = MainAdapter(this#CategoryQuran, modelMain, this )
rvListArticles!!.adapter = mainAdapter
}
private fun searchPosts(query: String) {
mainAdapter = MainAdapter(this#CategoryQuran, modelMain, this)
rvListArticles!!.adapter = mainAdapter
}
both show 'Type mismatch: inferred type is CategoryQuran but MainAdapter.onSelectData! was expected'
Can you guys help me? please
Ok so the problem is i am have to add OnSelectData in my Class, in my case what i have to do is add MainAdaper.OnSelectData
so Before it like :
class CategoryQuran : AppCompatActivity() {
and after it like :
class CategoryQuran : AppCompatActivity(), MainAdapter.OnSelectData {
thats my fault, im too rush when i coding it

i want to add next page (every page is 10) to my recyclerview but it delet my last page

my recyclerview fragment:
this is the fragment that I set my recycler view , I want when touch the continue button (btn_continue) add the rest of the list, which is actually the next page, to my list when I click the button
But it deletes the previous list and displays the new list
and i use the kotlin coruotine, viewmodel and recyclerview
class AllUnpublishedAdsFragment : Fragment() {
lateinit var unpublishedAdsAdapter: UnpublishedAdsAdapter
var items = ArrayList<M_Ads>()
lateinit var loadMoreItems: ArrayList<M_Ads>
lateinit var scrollListener: RecyclerViewLoadMoreScroll
lateinit var mLayoutManager: RecyclerView.LayoutManager
val page = "1"
var newpage = page.toInt()
var navController: NavController? = null
lateinit var btn_continue: Button
private lateinit var viewModel: MainViewmodels
lateinit var token: String
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_all_unpublished_ads, container,
false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btn_continue = view.findViewById<Button>(R.id.btn_continueAds)
token = arguments?.getString(TOKEN_KEY).toString()
Log.i("TOKEN", token)
setupViewModel(token, page)
continueAds()
unpublishedAdsAdapter.itemClickListener = { item, position ->
val id = item.id
val bundle_id = Bundle()
bundle_id.putString(ID_KEY, id.toString())
navController = Navigation.findNavController(view)
//view.findNavController().navigate(R.id.action_UnpublishedAds_to_Detail,
bundle_id)
navController!!.navigate(
R.id.action_allUnpublishedAdsFragment_to_adsDetailFragment,
bundle_id
)
}
}
private fun setupViewModel(token: String, page: String) {
LoadingDialog.show(requireContext(), { ld ->
recy_unpublished_ads.layoutManager = LinearLayoutManager(activity)
val decoration = DividerItemDecoration(activity, DividerItemDecoration.VERTICAL)
recy_unpublished_ads.addItemDecoration(decoration)
viewModel = ViewModelProvider(this).get(MainViewmodels::class.java)
unpublishedAdsAdapter = UnpublishedAdsAdapter()
recy_unpublished_ads.adapter = unpublishedAdsAdapter
viewModel.adsListObserve().observe({ lifecycle }, { model ->
items.clear()
items.addAll(model.adsList!!)
unpublishedAdsAdapter.setUpdateData(items)
ld.dismiss()
btn_continue.visibility = View.VISIBLE
})
viewModel.getAdsList(token, page)
})
}
fun continueAds() {
var isTouched=false
btn_continue.setOnClickListener {
isTouched=true
newpage = newpage + 1
Log.i("CONTINUE", newpage.toString())
setupViewModel(token, newpage.toString())
unpublishedAdsAdapter.notifyDataSetChanged()
isTouched=false
}
}
RetrofitInstance class
class RetrofitInstance {
companion object{
fun getRetrofitInstance (): Retrofit{
// val interceptor = HttpLoggingInterceptor()
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
// val client: OkHttpClient = OkHttpClient.Builder().addInterceptor(interceptor).build()
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build()
return Retrofit.Builder()
.baseUrl(BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
}
}
}
my adapter:
class UnpublishedAdsAdapter : RecyclerView.Adapter<UnpublishedAdsAdapter.MyViewHolder>() {
var items = ArrayList<M_Ads>()
var itemClickListener: ((item: M_Ads, position: Int) -> Unit)? = null
lateinit var mcontext: Context
class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class LoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
fun setUpdateData(items: ArrayList<M_Ads>) {
this.items = items
notifyDataSetChanged()
}
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val img_ads = view.findViewById<ImageView>(R.id.img_recy_ads)
val txt_title = view.findViewById<TextView>(R.id.txt_recy_ads_title)
val txt_accountType = view.findViewById<TextView>(R.id.txt_recy_ads_acctype)
fun bind(data: M_Ads) {
txt_title.setText(data.title)
txt_accountType.setText(data.accountType)
if (!data.image1.equals("")) {
Picasso.with(img_ads.context).load(data.image1).into(img_ads)
} else {
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
mcontext = parent.context
return if (viewType == Constant.VIEW_TYPE_ITEM) {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.row_recy_unpublished_ads, parent, false)
MyViewHolder(view)
} else {
val view =
LayoutInflater.from(mcontext).inflate(R.layout.progress_loading, parent, false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
view.progressbar.indeterminateDrawable.colorFilter =
BlendModeColorFilter(Color.WHITE, BlendMode.SRC_ATOP)
} else {
view.progressbar.indeterminateDrawable.setColorFilter(
Color.WHITE,
PorterDuff.Mode.MULTIPLY
)
}
MyViewHolder(view)
}
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(items.get(position))
handleClick(holder)
}
fun handleClick(holder: UnpublishedAdsAdapter.MyViewHolder) {
holder.itemView.setOnClickListener {
val position = holder.adapterPosition
itemClickListener?.invoke(items.get(position), position)
}
}
override fun getItemCount(): Int {
return items.size
}
my Viewmodel:
class MainViewmodels:ViewModel() {
lateinit var getAds:MutableLiveData<Main_ModelAds>
init {
getAds= MutableLiveData<Main_ModelAds>()
}
fun adsListObserve():MutableLiveData<Main_ModelAds>{
return getAds
}
fun getAdsList(token:String,page:String){
viewModelScope.launch(Dispatchers.IO) {
try {
Log.i("ERRORRES",token + "")
val retrofitInstance=RetrofitInstance.getRetrofitInstance().create(RetrofitService::class.java)
val response=retrofitInstance.unPublishedAdsList(token,page)
getAds.postValue(response)
}catch (ex:Exception){
Log.i("ERRORRES", ex.message.toString() + "")
}
}
}
What you want here is to update the list that you are showing when the user clicks the button.
In this case you should use ListAdapter.
You can refer to this article for implementation:
https://developer.android.com/reference/androidx/recyclerview/widget/ListAdapter

how can i get a function to finish retrieving data before the rest of my code is executed [duplicate]

This question already has answers here:
getContactsFromFirebase() method return an empty list
(1 answer)
Setting Singleton property value in Firebase Listener
(3 answers)
Closed 2 years ago.
Im trying to get a method that gets data from firebase to finish executing before the rest of my code is run so that it can add the data to a spinner.
at the moment i'm using a call back but it seems that this only prints the data when all the data is fetched
this is my code and i've added some println()s to see the order of how the code is running:
class FollowingFragment: Fragment() {
private val database = FirebaseDatabase.getInstance()
private val mAuth = FirebaseAuth.getInstance()
private var currentUid = mAuth.currentUser?.uid
val sharedPreferences = activity?.getSharedPreferences("savedCategories", Context.MODE_PRIVATE)
val categories: ArrayList<String> = ArrayList()
val test: ArrayList<String> = ArrayList()
lateinit var spinner : Spinner
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) =
inflater.inflate(R.layout.fragment_following, container, false)!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
println("Order 1")
fetchUserFollowings(object:FollowingCallback {
override fun onCallback(value: ArrayList<String>) {
println("Order 2")
test.addAll(categories)
println(test)
println("Order 3")
}
})
println("Order 4")
//Bind views
val list = view.findViewById<RecyclerView>(R.id.followingRecyclerView)
//create layout manager
val layoutManager = LinearLayoutManager(context)
list.layoutManager = layoutManager
spinner = view.findViewById(R.id.sp_option) as Spinner
//Set Dropdown list
println("Order 5")
val adapter = ArrayAdapter<String>(view.context, android.R.layout.simple_list_item_1, test)
println("Order 6")
spinner.adapter = adapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
//fetchNews(categories[position])
//Log.e("CATEGORY", "${categories[position]}")
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}
}
}
private fun fetchNews(category: String) {
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val date = "$year-${month+1}-$day"
val dateBefore = "$year-${month+1}-${day-1}"
val url = "http://newsapi.org/v2/everything?q=$category&from=$dateBefore&to=$date&sortBy=popularity&apiKey=${Constants.API_KEY}"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
val body = response?.body?.string()
val gson = GsonBuilder().create()
val homeFeed = gson.fromJson(body, HomeFeed::class.java)
activity?.runOnUiThread {
followingRecyclerView.adapter = MyAdapter(homeFeed)
}
}
override fun onFailure(call: Call, e: IOException) {
println("Failed to execute request")
}
})
}
interface FollowingCallback {
fun onCallback(value:ArrayList<String>)
}
private fun fetchUserFollowings(myCallback:FollowingCallback) {
val myRef = database.getReference("User-following").child(currentUid!!)
myRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
categories.clear()
for (childSnapshot in dataSnapshot.children) {
if (childSnapshot.hasChildren()) {
var test = childSnapshot.child("category").value
categories.add(test as String)
}
}
myCallback.onCallback(categories)
}
override fun onCancelled(error: DatabaseError) {
Log.e("Database Error", error.toString())
}
})
}
}
this is how it prints out:
Order 1
Order 4
Order 5
Order 6
Order 2
["List of from firebase"]
Order 3
but i need the "list from firebase" before order 4,5,6 are run as i need to use this list to populate the spinner
how can i fix this?

Receive data from Adapter to DetailsActivity?

I want to know how I can receive the data from adapter (recyclerview) to DetailsActivity. I tried many times but the images from recyclerview doesn't show in DetailsActivity.
this is my code.
ImageAdapter
class ImageAdapter (private var items:List<Item>, private val context:Context):
RecyclerView.Adapter<ImageAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):ViewHolder {
return ViewHolder(
LayoutInflater.from(context).inflate(R.layout.item, parent, false)
)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ImageAdapter.ViewHolder, position: Int) {
val item = items[position]
Picasso.get().load(item.imageUrl).into(holder.imageView)
holder.imageView.setOnClickListener {
val intent = Intent(context, DetailsActivity::class.java)
intent.putExtra("iImages", item.imageUrl)
context.startActivity(intent)
}
}
class ViewHolder(view:View):RecyclerView.ViewHolder(view) {
val imageView : ImageView = view.findViewById(R.id.imageView)
}
}
DetailsActivity
class DetailsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
val aImageView = intent.getIntExtra("iImages", 0)
details_image.setImageResource(aImageView)
}
}
RecyclerActivity
class RecyclerActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler)
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference.child("wallpapers")
val imageList : ArrayList<Item> = ArrayList()
//progressBar.visibility = View.VISIBLE
val listAllTask : Task<ListResult> = storageRef.listAll()
listAllTask.addOnCompleteListener { result ->
val items: List<StorageReference> = result.result!!.items
//add cycle for add image url to list
items.forEachIndexed { index,item ->
item.downloadUrl.addOnSuccessListener {
Log.d("item", "$it")
imageList.add(Item(it.toString()))
}.addOnCompleteListener {
recyclerview.adapter = ImageAdapter(imageList, this)
recyclerview.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
//progressBar.visibility = View.GONE
}
}
}
}
}
Item
data class Item(
var imageUrl: String
)
The problem is this line:
details_image.setImageResource(aImageView)
You are setting a resource int but what you pass seems to be a url, so instead load the "iImages" value with Picasso for that view
Edit: Replace this:
val aImageView = intent.getIntExtra("iImages", 0)
details_image.setImageResource(aImageView)
with this
val retrievedImageUrl = intent.getIntExtra("iImages", 0)
Picasso.get().load(retrievedImageUrl).into(details_image)
The Answer
val imageView : ImageView = findViewById(R.id.details_image)
Glide.with(this).load(intent.getStringExtra("iImages")).into(imageView)

Item on recycler-view disappear after changing to a different activity and back again

A very newbie programmer here and not a good English typer. Im trying to create a checker for purchase that already made previous using the PurchaseHistoryResponseListener. And When a checker found something, it will add to a list and then feed the recyclerview_MYBook with that data. The issue is that when launching the app, the data is flow through the recyclerview_MYBook perfectly, but when moving to different activity and going back to the previous activity through a different method (button click) the data on the recyclerview_MYBook doesn't show up, only through a conventional back button, the data on the recyclerview show up. Below here is my noob code
class MainActivity : AppCompatActivity(), PurchasesUpdatedListener {
private lateinit var billingClient: BillingClient
private lateinit var blogadapternew: BlogRecyclerAdapterNew
private lateinit var blogadapterpremium: BlogRecyclerAdapterPremium
private lateinit var blogadapterfree: BlogRecyclerAdapterFree
private lateinit var blogadaptermybook: BlogRecyclerAdapterMyBook
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
auth = FirebaseAuth.getInstance()
//FirebaseAuth.getInstance().signOut()
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
setContentView(R.layout.activity_main)
recycler_viewNew.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL,false)
recycler_viewNew.adapter= BlogRecyclerAdapterNew()
recycler_viewPremium.layoutManager = LinearLayoutManager(this,RecyclerView.HORIZONTAL,false)
recycler_viewPremium.adapter= BlogRecyclerAdapterPremium()
recycler_viewFree.layoutManager = LinearLayoutManager(this,RecyclerView.HORIZONTAL,false)
recycler_viewFree.adapter= BlogRecyclerAdapterFree()
recycler_viewMyBook.layoutManager = LinearLayoutManager(this,RecyclerView.HORIZONTAL,false)
recycler_viewMyBook.adapter= BlogRecyclerAdapterMyBook()
if (supportActionBar != null)
supportActionBar?.hide()
setupBillingClient()
initrecyclerView()
initrecyclerViewPremium()
initrecyclerViewFree()
initrecyclerViewMyBook()
addDataSetNew()
addDataSetPremium()
addDataSetFree()
Logo.setOnClickListener{
val intent = Intent(MonstaLogo.context, MainActivity::class.java)
MonstaLogo.context.startActivity(intent)
}
MainFeaturedButton.setOnClickListener {
val intent = Intent(MainFeaturedButton.context, MainActivity::class.java)
MainFeaturedButton.context.startActivity(intent)
}
MainNewButton.setOnClickListener {
val intent = Intent(MainNewButton.context, NewActivity::class.java)
MainNewButton.context.startActivity(intent)
}
NewMore.setOnClickListener{
val intent = Intent(NewMore.context, NewActivity::class.java)
NewMore.context.startActivity(intent)
}
MainPremiumButton.setOnClickListener {
val intent = Intent(MainPremiumButton.context, PremiumActivity::class.java)
MainPremiumButton.context.startActivity(intent)
}
PremiumMore.setOnClickListener{
val intent = Intent(PremiumMore.context, PremiumActivity::class.java)
PremiumMore.context.startActivity(intent)
}
MainFreeButton.setOnClickListener {
val intent = Intent(MainFreeButton.context, FreeActivity::class.java)
MainFreeButton.context.startActivity(intent)
}
FreeMore.setOnClickListener {
val intent = Intent(FreeMore.context, FreeActivity::class.java)
FreeMore.context.startActivity(intent)
}
MainMyBookButton.setOnClickListener {
val intent = Intent(MainMyBookButton.context, MyBookActivity::class.java)
MainMyBookButton.context.startActivity(intent)
}
MyBookMore.setOnClickListener {
val intent = Intent(MyBookMore.context, MyBookActivity::class.java)
MyBookMore.context.startActivity(intent)
}
}
private fun setupBillingClient() {
billingClient = BillingClient.newBuilder(this)
.enablePendingPurchases()
.setListener(this)
.build()
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
println("Setup Billing Done")
PurchaseHistoryResponseListener()
}
}
override fun onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
println("Failed")
setupBillingClient()
println("Restart Connection")
}
})
}
override fun onPurchasesUpdated(
billingResult: BillingResult?,
purchases: MutableList<Purchase>?
) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private fun PurchaseHistoryResponseListener (){
billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP) {
responseCode, result ->
// println("queryPurchasesAsync INAPP results: ${result?.size}")
// println("Getting Purchase History")
println("$result")
val dataMyBook1 = DataSourceMyBook.createDataSet()
if ("testcode1" in result.toString()) {
println("found it 1")
dataMyBook1.add((BlogPost( "BookName","Link","No")))
}
if ("testcode2" in result.toString()) {
println("found it 2")
dataMyBook1.add((BlogPost( "BookName","Link","No")))
}
if ("testcode3" in result.toString()) {
println("found it 3")
dataMyBook1.add((BlogPost( "BookName","Link","No")))
}
blogadaptermybook.submitList(dataMyBook1)
println(dataMyBook1)
}
}
private fun addDataSetNew(){
val dataNew = DataSourceNew.createDataSet()
blogadapternew.submitList(dataNew)
}
private fun addDataSetPremium(){
val dataPremium = DataSourcePremium.createDataSet()
blogadapterpremium.submitList(dataPremium)
}
private fun addDataSetFree(){
val dataFree = DataSourceFree.createDataSet()
blogadapterfree.submitList(dataFree)
}
/*private fun addDataSetMyBook(){
val dataMyBook1 = DataSourceMyBook.createDataSet()
blogadaptermybook.submitList(dataMyBook1)
}*/
/*private fun addDataSetMyBook(){
val dataMyBook1 = DataSourceMyBook.createDataSet()
billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP) {
responseCode, result ->
println("$result")
if ("bbbg_s2_c1_testcode1" in result.toString()){
dataMyBook1.add((BlogPost( "Mini Comic 1","Link","No")))
}
if ("bbbg_s2_c1_testcode2" in result.toString()){
dataMyBook1.add((BlogPost( "Mini Comic 2","Link","No")))
}
if ("bbbg_s2_c1_testcode3" in result.toString()){
dataMyBook1.add((BlogPost( "Mini Comic 3","Link","No")))
}
blogadaptermybook.submitList(dataMyBook1)
}}*/
/*dataMyBook.add((BlogPost( "Mini Comic 1","Link","No")))
dataMyBook.add((BlogPost( "Mini Comic 1","Link","No")))
dataMyBook.add((BlogPost( "Mini Comic 1","Link","No")))*/
private fun initrecyclerView(){
recycler_viewNew.apply {
layoutManager = LinearLayoutManager(this#MainActivity,RecyclerView.HORIZONTAL,false)
val topSpacingItemDecoration = TopSpacingItemDecoration(padding = 30)
addItemDecoration(topSpacingItemDecoration)
blogadapternew = BlogRecyclerAdapterNew()
adapter = blogadapternew
}
}
private fun initrecyclerViewPremium(){
recycler_viewPremium.apply {
layoutManager = LinearLayoutManager(this#MainActivity,RecyclerView.HORIZONTAL,false)
val topSpacingItemDecoration = TopSpacingItemDecoration(padding = 30)
addItemDecoration(topSpacingItemDecoration)
blogadapterpremium = BlogRecyclerAdapterPremium()
adapter = blogadapterpremium
}
}
private fun initrecyclerViewFree(){
recycler_viewFree.apply {
layoutManager = LinearLayoutManager(this#MainActivity,RecyclerView.HORIZONTAL,false)
val topSpacingItemDecoration = TopSpacingItemDecoration(padding = 30)
addItemDecoration(topSpacingItemDecoration)
blogadapterfree = BlogRecyclerAdapterFree()
adapter = blogadapterfree
}
}
private fun initrecyclerViewMyBook(){
recycler_viewMyBook.apply {
layoutManager =
LinearLayoutManager(this#MainActivity, RecyclerView.HORIZONTAL, false)
val topSpacingItemDecoration = TopSpacingItemDecoration(padding = 30)
addItemDecoration(topSpacingItemDecoration)
blogadaptermybook = BlogRecyclerAdapterMyBook()
adapter = blogadaptermybook
}
}
public override fun onStart() {
super.onStart()
val currentUser = auth.currentUser
updateUI(currentUser)
}
private fun updateUI(currentUser: FirebaseUser?) {
if (currentUser != null) {
AccountSettingButton.setImageResource(R.drawable.profileicon)
}
}
}
Here is adapter
class BlogRecyclerAdapterMyBook : RecyclerView.Adapter() {
private var items: List<BlogPost> = ArrayList()
private var items2: List<BlogPost> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return BlogViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.layout_blog_list_item_mybook,
parent,
false
)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is BlogViewHolder -> {
holder.bind(items.get(position))
holder.bind(items2.get(position))
}
}
}
override fun getItemCount(): Int {
return items.size
}
fun submitList(bloglist: List<BlogPost>) {
items = bloglist
items2 = bloglist
}
class BlogViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
val blogImage: ImageButton = itemView.blog_imagemybook
val blogTitle: TextView = itemView.blog_titlemybook
val premiumImage: ImageView = itemView.premiumicon
fun bind(blogPost: BlogPost) {
blogTitle.setText(blogPost.title)
val requestOptions = RequestOptions()
.placeholder(R.drawable.mocksplash)
.error(R.drawable.disconnect)
Glide.with(itemView.blog_imagemybook)
.applyDefaultRequestOptions(requestOptions)
.load(blogPost.image)
.into(blogImage)
blogImage.setOnClickListener {
Toast.makeText(blogImage.context, "<<Swipe left<<", Toast.LENGTH_SHORT).show()
val intent = Intent(blogTitle.context, ComicReadingActivity::class.java)
var KomikName = blogTitle.text.toString()
intent.putExtra("KomikName",Name)
blogImage.context.startActivity(intent)
}
}
}
}
and here the data source file where that will store the data for the adapter
class DataSourceMyBook{
companion object{
fun createDataSet(): ArrayList<BlogPost> {
val dataMyBook1 = ArrayList<BlogPost>()
return dataMyBook1
}
}
}