Я хочу создать профиль в своем приложении, где я могу редактировать или добавлять некоторую информацию при входе в систему. Он уже работает с флажком, но не работает с другими элементами editText. Также я хочу показать сохраненную информацию после того, как закрыл приложение в профиле. Есть идеи, как я мог это сделать? Как изменить editText на textView или есть другой способ?

Вот мой код фрагмента профиля: (я пробовал несколько вариантов сохранения данных в базе данных firebase)

package com.example.discoverme

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.ContentValues.TAG
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.*
import androidx.fragment.app.Fragment
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.UserProfileChangeRequest
import com.google.firebase.database.*
import java.util.*
import java.util.Calendar.*


class ProfilFoto : Fragment() {

    lateinit var mDatabase : DatabaseReference
    var mAuth = FirebaseAuth.getInstance()
    var user = FirebaseAuth.getInstance().currentUser
    var DISPLAY_NAME : String? = null


    @SuppressLint("SetTextI18n", "ResourceType")
    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        //  setContentView(R.layout.fragment_notifications)
        val rootView: View = inflater.inflate(R.layout.fragment_profil_foto, container, false)


        Toast.makeText(this.requireContext(), "Profil", Toast.LENGTH_LONG)
        Log.e("Halllo", "Hat toll geklapptttt")
        
        val telefon = rootView.findViewById<View>(R.id.telnummer) as EditText
        val geburtstag = rootView.findViewById<View>(R.id.geburtsdatum) as EditText
        val location = rootView.findViewById<View>(R.id.locationPerson) as EditText
        val stundenlohn = rootView.findViewById<View>(R.id.stundenlohn) as EditText

        var tele = telefon.text.toString()
        var gebi = geburtstag.text.toString()
        var loc = location.text.toString()
        var stundenl = stundenlohn.text.toString()

        val nameTxt: TextView = rootView.findViewById(R.id.textName1)
        val emailTxt: TextView = rootView.findViewById(R.id.emailemail)
        val spezi = rootView.findViewById<TextView>(R.id.spezialisierungen)


        var uid = user!!.uid

        val userHashMap = HashMap<String, Any>()

        mDatabase = FirebaseDatabase.getInstance().getReference("User").child(uid)

        val speicherButton = rootView.findViewById<Button>(R.id.speichern)



        speicherButton.setOnClickListener {

            Log.e("Speichern", "speichert")


            Log.e("Telefon", tele)
                //userHashMap["Telefon"] = tele
                //mDatabase.child("Telefon").setValue(tele)

            mDatabase.child("Telefon").setValue(tele)
                    .addOnSuccessListener {
                        Log.e("Telefon", tele)
                    }
                    .addOnFailureListener {
                        Log.e("Telefon2", "failed")
                    }


        if (!gebi.isEmpty()) {

            Log.e("Geburtstag", gebi)

            userHashMap["Geburtsdatum"] = gebi

           // mDatabase.updateChildren(userHashMap)
        }

        if (!loc.isEmpty()) {

            userHashMap["Adresse"] = loc

          //  mDatabase.updateChildren(userHashMap)
        }

        if (!stundenl.isEmpty()) {

            userHashMap["Stundenlohn"] = stundenl

           // mDatabase.updateChildren(userHashMap)
        }

            mDatabase.updateChildren(userHashMap)



    }


        mDatabase.addValueEventListener(object : ValueEventListener {
            override fun onCancelled(error: DatabaseError) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onDataChange(snapshot: DataSnapshot) {
                nameTxt.text = snapshot.child("Name").value.toString()
                emailTxt.text = snapshot.child("Email").value.toString()





                if (snapshot.child("Spezialisierung").exists()) {
                    Log.e("Spez", "Ist anscheinend da")
                    spezi.text = snapshot.child("Spezialisierung").value.toString()
                }

               /* if (snapshot.child("Telefon").exists()) {

                    telefon.text = snapshot.child("Telefon").value.toString()
                }
*/

            }
        })

        val buttonSignOut : ImageButton? = rootView.findViewById(R.id.signOut_button1)


        if (buttonSignOut != null) {
            buttonSignOut.setOnClickListener{
                mAuth.signOut()
                Toast.makeText(this.context, "Signed Out", Toast.LENGTH_LONG).show()
                startActivity(Intent(this.context, Start::class.java))

            }

        }

        val buttonspezi = rootView.findViewById<Button>(R.id.buttonspez)



        buttonspezi.setOnClickListener { view ->
            var dialog: AlertDialog

            // Initialize an array of colors
            val arrayColors = arrayOf("Hochzeit", "Portrait", "Familien", "Architektur", "Passfotos", "Lebensmittel", "Film", "Interior", " Kinder/Babies", "Landschaft", "Mode", "People und Lifestyle", "Werbung", "Sport", "Produkte", "Akt")

            // Initialize a boolean array of checked items
            val arrayChecked = booleanArrayOf(false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false)


            var stringArray = arrayOf<String>()
            // Initialize a new instance of alert dialog builder object
            val builder = AlertDialog.Builder(this.context)

            // Set a title for alert dialog
            builder.setTitle("Gib seine Spezialisierung an.")



            // Define multiple choice items for alert dialog
            builder.setMultiChoiceItems(arrayColors, arrayChecked) { dialog, which, isChecked ->
                // Update the clicked item checked status
                arrayChecked[which] = isChecked

                // Get the clicked item
                val color = arrayColors[which]


            }


            // Set the positive/yes button click listener
            builder.setPositiveButton("OK") { _, _ ->
                // Do something when click positive button
                spezi.text = "Deine Spezialisierungen sind.. \n"
                for (i in 0 until arrayColors.size) {
                    val checked = arrayChecked[i]
                    if (checked) {

                        stringArray += arrayOf(arrayColors[i])
                        spezi.text = "${spezi.text}" + stringArray.toString()

                    }
                }
                userHashMap["Spezialisierung"] = stringArray.asList()

                Log.e("Liste", stringArray.asList().toString())

                mDatabase.updateChildren(userHashMap)
            }


            // Initialize the AlertDialog using builder object
            dialog = builder.create()

            // Finally, display the alert dialog
            dialog.show()
        }

        
            return rootView

    }

        // Method to show an alert dialog with multiple choice list items
    

    // Extension function to show toast message
    fun Context.toast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

}

И вот xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/profil_foto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffff"
        android:orientation="vertical"
        tools:context=".ProfilFoto">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="259dp"
            android:background="#9C27B0"
            android:orientation="vertical"
            android:visibility="visible">


            <ImageButton
                android:id="@+id/signOut_button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="320dp"
                android:layout_marginLeft="350dp"
                android:background="#9C27B0"
                android:contentDescription="TODO"
                android:paddingTop="20dp"
                android:paddingEnd="20dp"
                android:paddingRight="20dp"
                android:src="@drawable/ic_baseline_logout_24"
                android:title="@string/sign_out"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:showAsAction="ifRoom"
                app:tint="#FFFFFF"
                tools:ignore="RtlSymmetry"
                tools:visibility="visible" />

            <ImageView
                android:id="@+id/logo4"
                android:layout_width="match_parent"
                android:layout_height="120dp"
                android:layout_gravity="center"
                android:layout_margin="10dp"
                android:contentDescription="@string/todo"
                android:src="@drawable/ic_profil_wei_" />

            <TextView
                android:id="@+id/textName1"
                android:layout_width="wrap_content"
                android:layout_height="39dp"
                android:layout_gravity="center_horizontal"
                android:textColor="#fff"
                android:textSize="21sp"
                android:textStyle="bold" />

            <Space
                android:layout_width="match_parent"
                android:layout_height="50dp" />

        </LinearLayout>


        <LinearLayout
            android:layout_width="360dp"
            android:layout_height="700dp"
            android:layout_gravity="center"
            android:layout_marginTop="45dp"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingLeft="25dp">

                <EditText
                    android:id="@+id/infotext"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical"
                    android:hint="Erzähle etwas über dich..."
                    android:paddingLeft="20dp">

                </EditText>


            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:orientation="horizontal"
                android:paddingLeft="25dp">

                <ImageView
                    android:layout_width="36dp"
                    android:layout_height="36dp"
                    android:src="@drawable/ic_baseline_location_on_24"
                    app:tint="#9C27B0" />

                <EditText
                    android:id="@+id/locationPerson"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:hint="Adresse"
                    android:paddingLeft="20dp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:orientation="horizontal"
                android:paddingLeft="25dp">

                <ImageView
                    android:layout_width="36dp"
                    android:layout_height="36dp"
                    android:background="#00FFFFFF"
                    android:src="@drawable/ic_baseline_cake_24"
                    app:tint="#9C27B0" />

                <EditText
                    android:id="@+id/geburtsdatum"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:hint="Geburtsdatum"
                    android:paddingLeft="20dp" />
            </LinearLayout>


                <EditText
                    android:id="@+id/telnummer"
                    android:layout_width="300dp"
                    android:layout_height="35dp"
                    android:background="@drawable/button_register_background"
                    android:drawableLeft="@drawable/ic_baseline_call_24"
                    android:drawablePadding="10dp"
                    android:ems="10"
                    android:hint="Telefonnummer"
                    android:paddingLeft="20dp" />


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:orientation="horizontal"
                android:paddingLeft="25dp">

                <ImageView
                    android:layout_width="36dp"
                    android:layout_height="36dp"
                    android:src="@drawable/ic_mail_full"
                    app:tint="#9C27B0" />

                <TextView
                    android:id="@+id/emailemail"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:paddingLeft="20dp" />


            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:orientation="horizontal"
                android:paddingLeft="25dp">

                <Button
                    android:id="@+id/buttonspez"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Spezialisierungen"
                    android:textAllCaps="false"
                    android:background="@drawable/buttom_rounded_corner_lila"
                    android:textColor="#FFFFFF"
                    android:layout_gravity="center_vertical|center_horizontal"
                    android:gravity="center"
                    />
                <TextView
                    android:id="@+id/spezialisierungen"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    style="@style/Base.TextAppearance.AppCompat.Large"
                    android:layout_margin="25dp"
                    />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:orientation="horizontal"
                android:paddingLeft="25dp">

                <ImageView
                    android:layout_width="36dp"
                    android:layout_height="36dp"
                    android:src="@drawable/ic_baseline_attach_money_24"
                    app:tint="#9C27B0" />

                <EditText
                    android:id="@+id/stundenlohn"
                    android:hint="Stundenlohn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:paddingLeft="20dp" />


            </LinearLayout>



                <Button
                    android:id="@+id/speichern"
                    android:layout_width="160dp"
                    android:layout_height="50dp"
                    android:layout_gravity="center"
                    android:layout_marginTop="25dp"
                    android:background="@drawable/buttom_rounded_corner_lila"
                    android:text="Änderungen speichern"
                    android:textColor="#FFFFFF"
                    app:cornerRadius="20dp">

                </Button>




        </LinearLayout>


        <Space
            android:layout_width="match_parent"
            android:layout_height="17dp" />


    </LinearLayout>
</ScrollView>
0
Luzie Ewert 12 Фев 2021 в 20:40

1 ответ

Лучший ответ

Я решил это. Мне просто нужно было переместить объявление findViewById внутри setOnClickListener, а не только в onCreate. Теперь я получаю информацию ediText и могу сохранить ее в своей базе данных firebase.

Вот так:

class ProfilFoto : Fragment() {

    lateinit var mDatabase : DatabaseReference
    var mAuth = FirebaseAuth.getInstance()
    var user = FirebaseAuth.getInstance().currentUser
    var DISPLAY_NAME : String? = null


    @SuppressLint("SetTextI18n", "ResourceType")
    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        //  setContentView(R.layout.fragment_notifications)
        val rootView: View = inflater.inflate(R.layout.fragment_profil_foto, container, false)


        Toast.makeText(this.requireContext(), "Profil", Toast.LENGTH_LONG)
        Log.e("Halllo", "Hat toll geklapptttt")



        val nameTxt: TextView = rootView.findViewById(R.id.textName1)
        val emailTxt: TextView = rootView.findViewById(R.id.emailemail)
        val spezi = rootView.findViewById<TextView>(R.id.spezialisierungen)


        var uid = user!!.uid

        val userHashMap = HashMap<String, Any>()

        mDatabase = FirebaseDatabase.getInstance().getReference("User").child(uid)

        val speicherButton = rootView.findViewById<Button>(R.id.speichern)



        speicherButton.setOnClickListener {

            val telefon = rootView.findViewById<View>(R.id.telnummer) as EditText
            val geburtstag = rootView.findViewById<View>(R.id.geburtsdatum) as EditText
            val location = rootView.findViewById<View>(R.id.locationPerson) as EditText
            val stundenlohn = rootView.findViewById<View>(R.id.stundenlohn) as EditText


            val tele = telefon.text.toString()
            val gebi = geburtstag.text.toString()
            val loc = location.text.toString()
            val stundenl = stundenlohn.text.toString()
            Log.e("Speichern", "speichert")

            if (!gebi.isEmpty()) {
                Log.e("Telefon", tele)
                //userHashMap["Telefon"] = tele
                //mDatabase.child("Telefon").setValue(tele)

                mDatabase.child("Telefon").setValue(tele)
                        .addOnSuccessListener {
                            Log.e("Telefon", tele)
                        }
                        .addOnFailureListener {
                            Log.e("Telefon2", "failed")
                        }
            }


            if (!gebi.isEmpty()) {

                Log.e("Geburtstag", gebi)

                //userHashMap["Geburtsdatum"] = gebi

                mDatabase.child("Geburtstag").setValue(gebi)
                        .addOnSuccessListener {
                            Log.e("Telefon", gebi)
                        }
                        .addOnFailureListener {
                            Log.e("Telefon2", "failed")
                        }

                // mDatabase.updateChildren(userHashMap)
            }

            if (!loc.isEmpty()) {

                Log.e("Location", loc)

                //userHashMap["Adresse"] = loc
                mDatabase.child("Adresse").setValue(loc)
                        .addOnSuccessListener {
                            Log.e("Telefon", loc)
                        }
                        .addOnFailureListener {
                            Log.e("Telefon2", "failed")
                        }

                //  mDatabase.updateChildren(userHashMap)
            }

            if (!stundenl.isEmpty()) {

                // userHashMap["Stundenlohn"] = stundenl

                mDatabase.child("Stundenlohn").setValue(stundenl)
                        .addOnSuccessListener {
                            Log.e("Telefon", stundenl)
                        }
                        .addOnFailureListener {
                            Log.e("Telefon2", "failed")
                        }
                // mDatabase.updateChildren(userHashMap)
            }

    }


        mDatabase.addValueEventListener(object : ValueEventListener {
            override fun onCancelled(error: DatabaseError) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onDataChange(snapshot: DataSnapshot) {
                nameTxt.text = snapshot.child("Name").value.toString()
                emailTxt.text = snapshot.child("Email").value.toString()





                if (snapshot.child("Spezialisierung").exists()) {
                    Log.e("Spez", "Ist anscheinend da")
                    spezi.text = snapshot.child("Spezialisierung").value.toString()
                }

               /* if (snapshot.child("Telefon").exists()) {

                    telefon.text = snapshot.child("Telefon").value.toString()
                }
*/

            }
        })

        val buttonSignOut : ImageButton? = rootView.findViewById(R.id.signOut_button1)


        if (buttonSignOut != null) {
            buttonSignOut.setOnClickListener{
                mAuth.signOut()
                Toast.makeText(this.context, "Signed Out", Toast.LENGTH_LONG).show()
                startActivity(Intent(this.context, Start::class.java))

            }

        }



Мне просто нужно выяснить, как отобразить сохраненную информацию в профиле после ее однократного сохранения.

0
Luzie Ewert 13 Фев 2021 в 14:57