I'm trying to show images from my Firebase Realtime Database storage. I've done this before with a previous version of my app, but the difference is how I implemented it. My adapter and arraylist class are exactly the same, but instead of using an activity I switched to using fragments.
What I essentially did was copy my old work and make the appropriate changes so I wouldn't run into errors, but unfortunately I ran into some. My images from Firebase are not showing up at all and I'm not sure what is the problem.
Adapter Class
class AbstractAdapter(private val mContext: Context, private val abstractList: ArrayList<Abstract>) : RecyclerView.Adapter<AbstractAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.abstract_image_view, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Glide.with(mContext)
.load(abstractList[position].abstract)
.into(holder.imageView)
}
override fun getItemCount(): Int {
return abstractList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var imageView: ImageView = itemView.findViewById(R.id.abstractImageView)
}
companion object {
private const val Tag = "RecyclerView"
}
}
Data class
class Abstract {
var abstract: String? = null
constructor() {}
constructor(abstract: String?) {
this.abstract = abstract
}
}
Fragment in which images will be shown
class AbstractWallpapers: Fragment(), PurchasesUpdatedListener {
private lateinit var subscribeAbstract: Button
private var billingClient: BillingClient? = null
lateinit var recyclerView: RecyclerView
lateinit var abstractlist: ArrayList<Abstract>
private var recyclerAdapterAbstract: AbstractAdapter? = null
private var myRef3: DatabaseReference? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_abstract_wallpaper, container, false)
recyclerView = requireView().findViewById(R.id.abstract_recyclerView)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.abstract_recyclerView)
val layoutManager = LinearLayoutManager(requireActivity())
recyclerView.layoutManager = layoutManager
recyclerView.setHasFixedSize(true)
myRef3 = FirebaseDatabase.getInstance().reference
abstractlist = ArrayList()
ClearAll()
GetDataFromFirebase()
subscribeAbstract = view.findViewById(R.id.abstract_subscribe_btn)
subscribeAbstract.setOnClickListener {
subscribeAbstract()
}
// Establish connection to billing client
//check subscription status from google play store cache
//to check if item is already Subscribed or subscription is not renewed and cancelled
billingClient = BillingClient.newBuilder(requireActivity()).enablePendingPurchases().setListener(this).build()
billingClient!!.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
val queryPurchase = billingClient!!.queryPurchases(BillingClient.SkuType.SUBS)
val queryPurchases = queryPurchase.purchasesList
if (queryPurchases != null && queryPurchases.size > 0) {
handlePurchases(queryPurchases)
} else {
saveSubscribeValueToPref(false)
}
}
}
override fun onBillingServiceDisconnected() {
Toast.makeText(requireActivity(), "Service Disconnected", Toast.LENGTH_SHORT).show()
}
})
//item subscribed
if (subscribeValueFromPref) {
subscribeAbstract.visibility = View.GONE
} else {
subscribeAbstract.visibility = View.VISIBLE
}
}
// Code related to Firebase
#SuppressLint("NotifyDataSetChanged")
private fun GetDataFromFirebase() {
val query: Query = myRef3!!.child("Abstract")
query.addListenerForSingleValueEvent(object : ValueEventListener {
#SuppressLint("NotifyDataSetChanged")
override fun onDataChange(snapshot: DataSnapshot) {
for (dataSnapshot: DataSnapshot in snapshot.children) {
val abstract = Abstract()
abstract.abstract = dataSnapshot.child("abstract").value.toString()
abstractlist.add(abstract)
}
recyclerAdapterAbstract = abstractlist.let { AbstractAdapter(requireActivity(), it) }
recyclerView.adapter = recyclerAdapterAbstract
recyclerAdapterAbstract!!.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {}
})
if (recyclerAdapterAbstract != null) recyclerAdapterAbstract!!.notifyDataSetChanged()
}
private fun ClearAll() {
abstractlist.clear()
abstractlist = ArrayList()
}
I fixed my problem. It turns out my rules in Firebase Realtime Database rules for read were set to false instead. My code works perfect. It was only a stupid error on my part.
Related
`Hello friends, good morning. What should I do to restart the pedometer? I saw many samples, but what they all had in common was to click on the desired view to restart the pedometer. But I do not want that to happen. The number of steps should be 0 every 24 hours. My codes:
Thanks for the code to explain
class Home : Fragment(), SensorEventListener {
lateinit var binding: FragmentHomeBinding
private var sensorManager: SensorManager? = null
private var running = false
private var totalStep = 0f
private var previousTotalStep = 0f
//
private lateinit var mHandler: Handler
private var calories = 0.0
val todayDate: String = DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date())
val dateForCalories = "$todayDate-kcal"
override fun onResume() {
super.onResume()
running = true
val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//load View model
detailsViewModel.messageTodayLiveData.observe(viewLifecycleOwner) {
binding.homeLayout.messageDay.text = it.message
}
materialDrawer()
loadData()
resetSteps()
calculateCalories()
sensorManager = requireContext().getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
private fun resetSteps() {
}
private fun saveDate() {
Constant.editor(requireContext()).putFloat(STEPNUMBER, previousTotalStep).apply()
}
private fun loadData() {
previousTotalStep = Constant.getSharePref(requireContext()).getFloat(STEPNUMBER, 0f)
}
override fun onSensorChanged(event: SensorEvent?) {
if (running)
totalStep = event!!.values[0]
val currentSteps = totalStep.toInt() - previousTotalStep.toInt()
binding.homeLayout.txtSteps.text = ("$currentSteps")
binding.homeLayout.txtKilometers.text =
String.format(getString(R.string.meters_today), stepsToMeters(currentSteps))
binding.homeLayout.progressStep.apply {
setProgressWithAnimation(currentSteps.toFloat())
}
}
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
}
}
Service codes
class MyService : Service(), SensorEventListener {
private var sensorManager: SensorManager? = null
private var running = false
private var totalStep = 0f
private var previousTotalStep = 0f
val todayDate: String = DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date())
private lateinit var sharedPref: SharedPreferences
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
try {
running = true
val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
} catch (e: Exception) {
}
return START_STICKY
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onSensorChanged(event: SensorEvent?) {
if (running) {
totalStep = event!!.values[0]
val currentSteps = totalStep.toInt() - previousTotalStep.toInt()
Constant.editor(this).putFloat(STEPNUMBER, previousTotalStep).apply()
}
}
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
TODO("Not yet implemented")
}
override fun stopService(name: Intent?): Boolean {
return super.stopService(name)
}
override fun onDestroy() {
val intent = Intent(this, MyPhoneReceiver::class.java)
sendBroadcast(intent)
super.onDestroy()
}
}
Broadcast codes
class MyPhoneReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action?.equals(Intent.ACTION_BOOT_COMPLETED, ignoreCase = true) == true) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(Intent(context, MyService::class.java))
} else {
context.startService(Intent(context, MyService::class.java))
}
}
}
}
When I try to view the list of data coming from realtime firebase no information is displayed
My adapter:
class MarcacaoAdapter: RecyclerView.Adapter<MarcacaViewHolder>() {
private var items = listOf<Marcacao>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MarcacaViewHolder {
val view = LayoutInflater
.from(parent.context)
.inflate(R.layout.item_lista, parent, false)
return MarcacaViewHolder(view)
}
override fun onBindViewHolder(holder: MarcacaViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int {
return items.size
}
}
My view holder:
class MarcacaViewHolder(view: View): RecyclerView.ViewHolder(view) {
private val textviewData = itemView.findViewById<TextView>(R.id.tvDataM)
private val textviewHora = itemView.findViewById<TextView>(R.id.tvHoraM)
fun bind (item: Marcacao){
textviewData.text = item.dia
textviewHora.text = item.hora
}
}
My activity list:
class ListaActivity : AppCompatActivity() {
private val adapterMarcacao = MarcacaoAdapter()
private var tvDataM: TextView? = null
private var tvHoraM: TextView? = null
private lateinit var mDatabaseReference: DatabaseReference
private lateinit var mRecycler : RecyclerView
private lateinit var mArrayList : ArrayList<Marcacao>
override fun onCreate(savedInstanceState : Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lista)
mRecycler = findViewById(R.id.recyclerView)
mArrayList = arrayListOf<Marcacao>()
mDatabaseReference = FirebaseDatabase.getInstance().getReference("data")
}
}
I would like some help to identify why my recycler view is not loading information from firebase.
I have made an app that uses an API to make a request and then shows the results in a RecyclerView.
I was following a tutorial and in it they used a differCallback and a liveData so the lists updates and such. However whenever the user makes a second search, the recyclerView should only show the new results but the previous results don't dissapear and the new results just appear below the previous search.
I have debugged it for quite some time now but I don't seem to understand where the list is made and where sure it be updated (or in this case cleared).
I tried using .clear() for the diff (Asynclistdiffer), creating a new list in the onBindViewHolder and then clearing that list every time the "search" is called but without any luck. As im still a beginner I don't have a clue on where or what is happening, all your helo will be greatly appreciated
this is my adapter:
class RecipePreviewAdapter : RecyclerView.Adapter<RecipePreviewAdapter.RecipePreviewViewHolder>() {
inner class RecipePreviewViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
private val differCallback = object : DiffUtil.ItemCallback<Recipe>() {
override fun areItemsTheSame(oldItem: Recipe, newItem: Recipe): Boolean {
return oldItem.sourceUrl == newItem.sourceUrl
}
override fun areContentsTheSame(oldItem: Recipe, newItem: Recipe): Boolean {
return oldItem == newItem
}
}
val differ = AsyncListDiffer(this, differCallback)
lateinit var recipeList: MutableList<Recipe>
var isRecipeListInitialized = false
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecipePreviewViewHolder {
return RecipePreviewViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_recipe_preview,
parent,
false
)
)
}
override fun onBindViewHolder(holder: RecipePreviewViewHolder, position: Int) {
recipeList = differ.currentList.toMutableList()
isRecipeListInitialized = true
// Log.d(TAG, recipeList.toString())
val recipe = recipeList[position]
holder.itemView.apply {
Glide.with(this).load(recipe.image).into(ivRecipeImagePreview)
tvRecipeTitlePreview.text = recipe.title
tvTimeToMakeTVPreview.text = "${recipe.readyInMinutes} minutes"
tvSummaryPreview.text = Jsoup.parse(recipe.summary).text()
setOnClickListener {
onItemClickListener?.let { it(recipe) }
}
}
}
override fun getItemCount(): Int {
return differ.currentList.size
}
And this is where I call it:
class SearchRecipeFragment : Fragment(R.layout.fragment_search_recipe) {
lateinit var viewModel: RecipeViewModel
lateinit var recipeAdapter: RecipePreviewAdapter
val TAG = "SearchRecipeFragment"
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = (activity as RecipesActivity).viewModel
setupRecyclerView()
recipeAdapter.setOnItemClickListener {
val bundle = Bundle().apply {
putSerializable("recipe", it)
}
findNavController().navigate(
R.id.action_searchRecipeFragment_to_recipeFragment,
bundle
)
}
etSearch.setOnKeyListener(View.OnKeyListener { _, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
if (etSearch.text.toString().isNotEmpty()) {
viewModel.searchRecipe(etSearch.text.toString())
}
return#OnKeyListener true
}
false
})
viewModel.searchRecipeLiveData.observe(viewLifecycleOwner, Observer { response ->
when (response) {
is Resource.Success -> {
hideProgressBar()
response.data?.let { recipeResponse ->
recipeAdapter.differ.submitList(recipeResponse.results.toList())
}
}
is Resource.Error -> {
hideProgressBar()
response.message?.let { message ->
Log.e(TAG, "An error occurred: $message")
Toast.makeText(activity, "An error occurred: $message", Toast.LENGTH_LONG)
.show()
}
}
is Resource.Loading -> {
showProgressBar()
}
}
})
}
Ans this is the part of the ViewModel that I'm not really sure what it does
private fun handleSearchRecipeResponse(response: Response<SearchRecipeResponse>): Resource<SearchRecipeResponse> {
if (response.isSuccessful) {
response.body()?.let { resultResponse ->
searchRecipesPage++
if (searchRecipesResponse == null) {
searchRecipesResponse = resultResponse
} else {
val oldRecipes = searchRecipesResponse?.results
val newRecipes = resultResponse.results
oldRecipes?.addAll(newRecipes)
}
return Resource.Success(searchRecipesResponse ?: resultResponse)
}
}
return Resource.Error(response.message())
}
too late but it is because of "searchRecipesResponse". You have to set it to "null" and reset searchRecipesPage to 1 for each new search in etSearch.setOnKeyListener().
I have a class called medicine, I got an error when writing adapter = MedicineAdapter(this, this.medicineList!!) in main activity I saw the error in run window.
My app is crashing when I want to run and I saw one error which is about adapter's line
Also, I have medicine_items it is my custom design I assigned it to the adapter in my adapter also I checked my ids but ı don t know why am I got an error
MainActivity
class MainActivity : AppCompatActivity() {
private var adapter: MedicineAdapter? = null
private var medicineList : ArrayList<Medicine>? = null
private var recyclerView: RecyclerView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView =
findViewById<View>(R.id.recycler) as RecyclerView
adapter = MedicineAdapter(this, this.medicineList!!)
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView!!.layoutManager = layoutManager
recyclerView!!.itemAnimator = DefaultItemAnimator()
// Add a neat dividing line between items in the list
recyclerView!!.addItemDecoration(
DividerItemDecoration(this,
LinearLayoutManager.VERTICAL))
// set the adapter
recyclerView!!.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.addBtn -> {
val intent = Intent(this,AddNewMedicine::class.java)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
fun addMedicine(m: Medicine){
medicineList!!.add(m)
adapter!!.notifyDataSetChanged()
}
}
MyAdapter
class MedicineAdapter(
private val mainActivity: MainActivity,
private val medicineList: ArrayList<Medicine>)
: RecyclerView.Adapter<MedicineAdapter.ListItemHolder>(){
override fun onCreateViewHolder(
parent: ViewGroup, viewType: Int): ListItemHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.medicine_items, parent, false)
return ListItemHolder(itemView)
}
inner class ListItemHolder(view: View) :
RecyclerView.ViewHolder(view),
View.OnClickListener {
internal var name = view.findViewById<TextView>(R.id.name)
internal var amount = view.findViewById<TextView>(R.id.amount)
internal var description = view.findViewById<TextView>(R.id.description)
init {
view.isClickable = true
view.setOnClickListener(this)
}
override fun onClick(view: View) {
//val intentToCarPager = Intent(view!!.context, CarPagerActivity::class.java)
//view.context.startActivity(intentToCarPager)
}
}
override fun onBindViewHolder(holder: ListItemHolder, position: Int) {
val medicine = medicineList!![position]
holder.name.text = medicine.name.toString()
holder.amount.text = medicine.amount.toString()
holder.description.text = medicine.desription.toString()
}
override fun getItemCount(): Int {
if (medicineList != null) {
return medicineList.size
}
return -1
}
}
my run window
It's because here:
private var medicineList : ArrayList<Medicine>? = null
you have initialized medicineList as null and you haven't given it a proper value along the way and here:
adapter = MedicineAdapter(this, this.medicineList!!)
you have asserted that it is not null and tried to assign it to the adapter.
If you have no elements to add to your array at first, initialize it this way:
private var medicineList : ArrayList<Medicine> = arrayListOf()
and then you can add elements to it:
medicineList.add(myMedicine)
I Want to get Data from https://www.thesportsdb.com/api/v1/json/1/eventspastleague.php?id=4328
But I have error
java.lang.IllegalArgumentException: Parameter specified as non-null is
null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull,
parameter data at
com.yutra.jadwalbola.last_match.LastMatchFragment.showTeamList(Unknown
Source:21) at
com.yutra.jadwalbola.last_match.LastMatchPresenter$getTeamList$1$1.invoke(LastMatchPresenter.kt:21)
at
com.yutra.jadwalbola.last_match.LastMatchPresenter$getTeamList$1$1.invoke(LastMatchPresenter.kt:8)
this is my LastMatchDBApi
object LastMatchDBApi {
fun getMatch(): String {
return Uri.parse(BuildConfig.BASE_URL).buildUpon()
.appendPath("api")
.appendPath("v1")
.appendPath("json")
.appendPath(BuildConfig.TSDB_API_KEY)
.appendPath("eventspastleague.php")
.appendQueryParameter("id", "4328")
.build()
.toString()
}
}
this is my serialized
data class LastMatch(
#SerializedName("strEvent")
var eventName: String? = null
)
this is my presenter
class LastMatchPresenter(private val view: MainView,
private val apiRepository: ApiRepository,
private val gson: Gson) {
fun getTeamList() {
view.showLoading()
doAsync {
val data = gson.fromJson(apiRepository
.doRequest(LastMatchDBApi.getMatch()),
LastMatchResponse::class.java
)
uiThread {
view.hideLoading()
view.showTeamList(data.lastMatch)
}
}
}
}
this is my response
data class LastMatchResponse(
val lastMatch: List<LastMatch>
)
this is my fragment activity
class LastMatchFragment : Fragment(), MainView {
private lateinit var progressBar: ProgressBar
private lateinit var swipeRefresh: SwipeRefreshLayout
private var lastMatch: MutableList<LastMatch> = mutableListOf()
private lateinit var adapter: MainAdapter
private lateinit var listTeam: RecyclerView
private var key : String = "4328"
companion object {
fun newInstance(): LastMatchFragment {
return LastMatchFragment()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = UI {
linearLayout {
lparams (width = matchParent, height = wrapContent)
orientation = LinearLayout.VERTICAL
topPadding = dip(16)
leftPadding = dip(16)
rightPadding = dip(16)
// textView {
// text = "test image"
// }
relativeLayout{
lparams (width = matchParent, height = wrapContent)
listTeam = recyclerView {
lparams (width = matchParent, height = wrapContent)
layoutManager = LinearLayoutManager(ctx)
}
progressBar = progressBar {
}.lparams{
centerHorizontally()
}
}
}
}.view
adapter = MainAdapter(lastMatch)
listTeam.adapter = adapter
val request = ApiRepository()
val gson = Gson()
var presenter = LastMatchPresenter(this, request, gson)
presenter.getTeamList()
return view
}
override fun showLoading() {
progressBar.visible()
}
override fun hideLoading() {
progressBar.invisible()
}
override fun showTeamList(data: List<LastMatch>) {
lastMatch.clear()
lastMatch.addAll(data)
adapter.notifyDataSetChanged()
}
}
IF anyone have sourcode to get this data please help me
In below code you are passing list as null from LastMatchPresenter class
view.showTeamList(data.lastMatch)
By default all variables and parameters in Kotlin are non-null. If you want to pass null parameter to the method you should add ? to it's type, for example:
override fun showTeamList(data: List<LastMatch>?) {
lastMatch.clear()
lastMatch.addAll(data)
adapter.notifyDataSetChanged()
}