Why Firebase Realtime database is not working - android

I have written the code in Kotlin language
I need the firebase realtime database to add a child with user's UID with email as it's value under the users column when the user signs up. The Login is successful and then it passes to the main activity .The users details is listed in Authentication-> Users but the realtime database is not working and also when I click the back button it opens the main activity again and again ,after a number of clicks it goes back the login page and exits,maybe this is because it could not connect to the database.
Please help me with necessary changes.
Here is the code
MAIN ACTIVITY
private var mFirebaseAnalytics: FirebaseAnalytics?=null
class MainActivity : AppCompatActivity() {
var listofContacts = ArrayList<Contacts>()
var adapter: ContactsAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mFirebaseAnalytics= FirebaseAnalytics.getInstance(this)
listofContacts.add(Contacts("NAME", 123456789))
adapter = ContactsAdapter(this, listofContacts)
listview.adapter=adapter
}
inner class ContactsAdapter : BaseAdapter {
var contactslist = ArrayList<Contacts>()
var context: Context? = null
constructor(context: Context, contactslist: ArrayList<Contacts>) : super() {
this.contactslist = contactslist
this.context = context
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val contact = contactslist[position]
val inflater = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val myView = inflater.inflate(R.layout.contact_view, null)
myView.name.text = contact.name!!
myView.num.text = contact.num.toString()!!
myView.setOnClickListener {
val intent= Intent(context,ContactInfo::class.java!!)
intent.putExtra("name",contact.name!!)
intent.putExtra("num",contact.num!!)
context!!.startActivity(intent)
}
return myView
}
override fun getItem(position: Int): Any {
return contactslist[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return contactslist.size
}
}
}
LOGIN
private var mAuth:FirebaseAuth?=null
var database=FirebaseDatabase.getInstance()
var myRef=database.reference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
mAuth = FirebaseAuth.getInstance()
}
fun loginevent(view: View){
login(etun.text.toString(),pw.text.toString())
}
fun login(email:String,password:String){
mAuth!!.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this){task ->
if(task.isSuccessful){
Toast.makeText(applicationContext,"Login Successful", Toast.LENGTH_LONG).show()
LoadMain()
}
else
Toast.makeText(applicationContext,"Login Failed", Toast.LENGTH_LONG).show()
}
}
override fun onStart() {
super.onStart()
LoadMain()
}
fun LoadMain(){
var currentuser=mAuth!!.currentUser
if(currentuser!=null) {
myRef.child("Users").child(currentuser.uid).setValue(currentuser.email)
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("email", currentuser.email)
intent.putExtra("uid", currentuser.uid)
startActivity(intent)
}
}
}

Related

when i click imagebutton the image change. Can i save this change when i return again in this activity?

class suspect : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_suspect)
imagebutton.setOnClickListener {
imagebutton.setImageResource(R.drawable.picture2)
}
}
}
You could save an image identifier to Shared Preferences and then retrieve an image number from Shared Preferences when you open your activity. Then you use that number to set the ImageButton image.
I haven't ran this code, but something along the lines of this should work:
private val picture1Id = 1
private val picture2Id = 2
private val IMAGE_KEY = "IMAGE_KEY"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_suspect)
imagebutton.setOnClickListener {
saveImageIdentifier(picture2Id)
imagebutton.setImageResource(R.drawable.picture2)
}
setupImageButtonFromPreferences()
}
private fun saveImageIdentifier(id: Int) {
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putInt(IMAGE_KEY, id)
apply()
}
}
private fun getImageIdentifier(): Int {
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return 1
return sharedPref.getInt(IMAGE_KEY, 1)
}
private fun setupImageButtonFromPreferences() {
when (getImageIdentifier()) {
picture1Id -> imagebutton.setImageResource(R.drawable.picture1)
picture2Id -> imagebutton.setImageResource(R.drawable.picture2)
else -> return
}
}
var a = 0
class suspect : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_suspect)
if (a == 1){imagebutton.setImageResource(R.drawable.picture2)}
imagebutton.setOnClickListener {
imagebutton.setImageResource(R.drawable.picture2)
a = 1
}
imagebutton.setOnLongClickListener {
imagebutton.setImageResource(R.drawable.picture1)
a = 0
true
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("image", a)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
a = savedInstanceState.getInt("image")
}
}

Retrofit or Okhttp never called the link

So I got a problem, When the Main Page is shown, it's supposed to call the API to get the data from it. But, the API never called. What I find strange is, that before Main Page, there is a login page that successfully called the API for login. But, on Main Page, the Retrofit/Okhttp never called the Page to get the data. Do you guys know what's wrong?
Here's my code screenshot:
StoryPageSource
StoryRepository
ViewModel
StoryAdapter
MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var bind: ActivityMainBinding
private lateinit var storyAdapter: StoryAdapter
private val timelineStoryViewModel: TimelineStoryViewModel by viewModels {
ViewModelFactory(this, application)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bind = ActivityMainBinding.inflate(layoutInflater)
setContentView(bind.root)
showLoadingProcess(true)
displayStories()
bind.floatingActionButton.setOnClickListener {
startActivity(Intent(this, AddStoryActivity::class.java))
}
supportActionBar?.setTitle(R.string.app_name)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflaterMenu = menuInflater
inflaterMenu.inflate(R.menu.menus, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.app_bar_settings -> {
val context = this
val pref = context.getSharedPreferences(
R.string.token_pref.toString(),
Context.MODE_PRIVATE
)
val editor = pref.edit()
editor.remove(R.string.token.toString())
editor.remove(getString(R.string.email))
editor.remove(getString(R.string.password))
editor.apply()
startActivity(Intent(this, LoginActivity::class.java))
}
R.id.app_bar_maps -> {
startActivity(Intent(this, MapsActivity::class.java))
}
}
return super.onOptionsItemSelected(item)
}
private fun displayStories() {
showLoadingProcess(false)
storyAdapter = StoryAdapter()
bind.storyRV.layoutManager = LinearLayoutManager(this)
bind.storyRV.adapter = storyAdapter
timelineStoryViewModel.story().observe(this#MainActivity) { story ->
storyAdapter.submitData(lifecycle, story)
}
storyAdapter.setOnProfileCallback(object : StoryAdapter.OnProfileCallback {
override fun onProfileClicked(data: TimelineStory) {
chosenProfile(data)
}
})
}
private fun chosenProfile(story: TimelineStory) {
var name: TextView = findViewById(R.id.userName)
var storyPict: ImageView = findViewById(R.id.userImageStory)
val optionsCompat: ActivityOptionsCompat =
ActivityOptionsCompat.makeSceneTransitionAnimation(
this,
Pair(storyPict, getString(R.string.imageStoryDetail)),
Pair(name, getString(R.string.nama_pengguna)),
)
val sendData = Intent(this, StoryDetailActivity::class.java)
sendData.putExtra(StoryDetailActivity.EXTRA_STORY, story)
startActivity(sendData, optionsCompat.toBundle())
Toast.makeText(this, "Memuat Story " + story.name, Toast.LENGTH_SHORT).show()
}
private fun showLoadingProcess(isLoading: Boolean) {
if (isLoading) {
bind.loading.visibility = View.VISIBLE
} else {
bind.loading.visibility = View.GONE
}
}
}

The buttons of my introSlider aren't working, why is this happening - question Updated

I'm trying to build an app that has an intro slider when it's installed. I followed a tutorial.
However, I have an error and the app doesn't even open.
Here is some code:
Class Intro
class Intro : AppCompatActivity(), View.OnClickListener {
lateinit var mPager : ViewPager
var layouts : IntArray = intArrayOf(R.layout.first_slide,R.layout.second_slide,R.layout.third_slide)
lateinit var dotsLayout : LinearLayout
lateinit var dots: Array<ImageView>
lateinit var mAdapter : PageAdapter
lateinit var btnNext: Button
lateinit var btnSkip: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intro)
if(PrefManager(this).checkPreferences()){goToHomePage()}
if(Build.VERSION.SDK_INT >=19)
{
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
}else{
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
}
mPager=findViewById(R.id.pager)
mAdapter= PageAdapter(layouts,this)
mPager.adapter= mAdapter
dotsLayout = findViewById(R.id.dots)
btnNext = findViewById(R.id.btnNext)
btnSkip=findViewById(R.id.btnSkip)
btnSkip.setOnClickListener { this }
btnNext.setOnClickListener { this }
createDots(0)
mPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
createDots(position)
if(position == layouts.size){
btnNext.setText("DONE")
btnSkip.visibility=View.INVISIBLE
}else{
btnNext.setText("NEXT")
btnSkip.visibility=View.VISIBLE
}
}
})
}
fun createDots(position:Int){
if(dotsLayout!=null){
dotsLayout.removeAllViews()
}
dots = Array(layouts.size,{i -> ImageView(this)})
for(i in 0..layouts.size -1) {
dots[i] = ImageView(this)
if (i == position) {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_dots))
} else {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.inactive_dots))
}
var params: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
params.setMargins(4,0,4,0)
dotsLayout.addView(dots[i],params)
}
}
override fun onClick(v: View?) {
when(v!!.id){
R.id.btnSkip ->{
goToHomePage()
PrefManager(this).writeSharedPreferences()
}
R.id.btnNext ->{
loadNextSlide()
}
}
}
private fun goToHomePage() {
startActivity(Intent(this, HomePage::class.java))
finish()
}
private fun loadNextSlide() {
var nextSlide: Int = mPager.currentItem+1
if(nextSlide<layouts.size){
mPager.setCurrentItem(nextSlide)
}
else{
goToHomePage()
PrefManager(this).writeSharedPreferences()
}
}
}
Class PrefManager
class PrefManager {
lateinit var context : Context
lateinit var pref: SharedPreferences
constructor(context: Context) {
this.context = context
getSharedPreferences()
}
private fun getSharedPreferences(){
pref = context.getSharedPreferences(context.getString(R.string.pref_name), Context.MODE_PRIVATE)
}
fun writeSharedPreferences(){
var editor : SharedPreferences.Editor=pref.edit()
editor.putString(context.getString(R.string.pref_key),"NEXT")
editor.commit()
}
fun checkPreferences() : Boolean
{
var status: Boolean = false
status = !pref.getString(context.getString(R.string.pref_key),null).equals("null")
return status
}
fun clearPreferences(){
pref.edit().clear().commit()
context.startActivity(Intent(context, HomePage::class.java))
(context as AppCompatActivity).finish()
}
}
The app works but the buttons next and skip don't respond whe clicked. Why is this happening?
Update: I changed some redundant thing on the code and uncommented the part that I've previous commented, and I don't have the error anymore. But the buttons still don't work

Property not being initalized sometimes

I'm trying to handle fragment clicks in FragmentPagerAdapter, but sometimes I'm getting Fatal Exception: kotlin.UninitializedPropertyAccessException, which says that click listener property is not initialized.
So here is code for the PagerAdapter
class ApplicationListPagerAdapter(
fm: FragmentManager,
private val onListItemClick: (isSent: Boolean, application: Application) -> Unit,
private val onGoToScholarshipsTabClicked: () -> Unit,
private val onGoToPicksTabClicked: () -> Unit
): FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT),
ApplicationListFragment.ClickListener {
override fun getCount(): Int {
return 2
}
override fun getItem(position: Int): Fragment {
val isSent = position == 1
val fragment = ApplicationListFragment.newInstance(isSent)
fragment.setApplicationSelectListener(this)
return fragment
}
override fun getPageTitle(position: Int): CharSequence? {
return if (position == 0) "PICKS" else "SENT"
}
override fun applicationSelected(isSent: Boolean, application: Application) {
onListItemClick(isSent, application)
}
override fun goToScholarshipsTabClicked() {
onGoToScholarshipsTabClicked()
}
override fun goToPicksTabClicked() {
onGoToPicksTabClicked()
}
}
Code how I initialize it in fragment
private lateinit var clickListener: ClickListener
fun setApplicationSelectListener(clickListener: ClickListener) {
this.clickListener = clickListener
}
interface ClickListener {
fun applicationSelected(isSent: Boolean, application: Application)
fun goToScholarshipsTabClicked()
fun goToPicksTabClicked()
}
And here in onClick callback I'm getting crashes sometimes for some users.
private fun initRecyclerView(applications: List<Application>) {
application_list_recyclerView.adapter = ApplicationListItemsAdapter(
context!!,
applications.toMutableList(),
isSent,
this,
applicationViewModel.applicationService,
onClick = {
clickListener.applicationSelected(isSent, it)
},
onDelete = { application: Application, count: Int ->
scholarshipViewModel.unFavoriteScholarship(application.scholarship)
sharedViewModel.deletePickedScholarship(application.scholarship)
applicationSharedViewModel.updatePicksCount(count)
if (count == 0) {
showNoApplicationsFragment()
}
},
onUndoDelete = { application: Application, count: Int ->
sharedViewModel.undoDeletedScholarship(application.scholarship)
applicationSharedViewModel.updatePicksCount(count)
if (count == 1) {
hideNoApplicationsFragment()
}
}
)
application_list_recyclerView.layoutManager = LinearLayoutManager(context!!)
}
Thanks for any advice and I hope my explanation makes senes for everybody
Interface
interface OnItemClickListener {
//just a random method
fun itemClicked(positon: Int)
}
Inside Your Adapter class
private lateinit var listener: OnItemClickListener
fun attachListener(listener: OnItemClickListener){
this.listener = listener
}
Acticity/ Fragment
class MainActivity(): AppCompatActivity(), OnItemClickListener{
// implement interface in case you wanna use methods...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
// calling the listener method
myAdapter.attachListener(this)
}
}
above myAdapter is your adapter must be init first which is associate to your adapter class

Why l can`t set listener in Kotlin?

I have OnClickInterface (with method fun onClickShape()) Main.class, and FlipFragment.class and ImageView (which called image in my code). My goal is make listener for image.
interface OnClickInterface {
fun onClickShape()
}
MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initTabs()
var flip = FlipFragment()
flip.listener = object : OnClickInterface {
override fun onClickShape() {
Log.d("MainActivity", "Shape Pressed")
ToastUtils.showSuccessMessage(baseContext, "sometext")
}
}
}
fun initTabs() {
var adapter = TabsPagerFragmentAdapter(supportFragmentManager)
mViewPager.adapter = adapter
mTabLayout.setupWithViewPager(mViewPager)
}
}
onCreate in FlipFragment
var image = view.findViewById<ImageView>(R.id.fShapeView)
image.setOnClickListener(View.OnClickListener {
Log.d("FlipFragment", "PRESSED")
if (listener != null)
listener!!.onClickShape()
})
App was loading well, without errors. But when I pressed in the image I show in my log FlipFragment: PRESSED that's mean that my application call method from FragmentFlip, not override method from MainActivity. Why?
I searched error . My app show NPE here.
flip.listener = object : OnClickInterface {
override fun onClickShape() {
Log.d("MainActivity", "Shape Pressed")
ToastUtils.showSuccessMessage(baseContext, "someText")
}}
Why listener = null . I defined it with anonymous class.
All code in FlipFragment
class FlipFragment : Fragment() {
private var layout = R.layout.view_flip
var listener: OnClickInterface? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
var view: View
view = inflater!!.inflate(layout, container, false)
var image = view.findViewById<ImageView>(R.id.fShapeView)
image.setOnClickListener(View.OnClickListener {
Log.d("FlipFragment", "PRESSED")
if (listener != null){
listener!!.onClickShape()}
})
return view
}
companion object {
fun getInstanse(): FlipFragment {
var args = Bundle()
var flipFragment = FlipFragment()
flipFragment.arguments = args
return flipFragment
}
}
}
If you need all code it is FragmentPagerAdapter.class
class TabsPagerFragmentAdapter(fm: FragmentManager?) : FragmentPagerAdapter(fm) {
var tabs: Array<String> = arrayOf("Flip", "Multi")
override fun getItem(position: Int) = when(position){
0 -> FlipFragment.getInstanse()
1 -> Mulit.getInstanse() //it is empty now
else -> FlipFragment.getInstanse()
}
override fun getPageTitle(position: Int) = tabs[position]
override fun getCount() = tabs.size
}

Categories

Resources