android 在Kotlin中从Sqlite数据库检索时不膨胀布局

a2mppw5e  于 2023-05-12  发布在  Android
关注(0)|答案(1)|浏览(103)

我正在使用一个功能,这是当用户注册他们的电子邮件和密码,将被保存在sqlite,并可以在活动中检索命名的帐户管理器。我正在使用Kotlin进行编码,我只是根据sqlite中的数据扩展布局。电子邮件和密码已成功添加,但布局膨胀在回收视图中不起作用。布局没有膨胀。PFB屏幕截图Activity Without Layout Inflated
我的DataBaseHolder类:

package adapter

    import android.database.sqlite.SQLiteOpenHelper
    import adapter.DataBaseHolder
    import android.database.sqlite.SQLiteDatabase
    import android.content.ContentValues
    import android.content.Context
    import android.database.Cursor
    import android.widget.Toast

    class DataBaseHolder(private val context: Context?) : SQLiteOpenHelper(
        context, name, null, Database_VERSION
    ) {
        override fun onCreate(DB: SQLiteDatabase) {
            val query = "CREATE TABLE " + TABLE_NAME +
                    " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_EMAIL + " TEXT, " +
                    COLUMN_PASSWORD + " TEXT);"
            DB.execSQL(query)
        }

        override fun onUpgrade(DB: SQLiteDatabase, i: Int, i1: Int) {
            DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
            onCreate(DB)
        }

        fun add(email: String?, password: String?) {
            val DB = this.writableDatabase
            val cv = ContentValues()
            cv.put(COLUMN_EMAIL, email)
            cv.put(COLUMN_PASSWORD, password)
            val result = DB.insert(TABLE_NAME, null, cv)
            if (result == -1L) {
                Toast.makeText(context, "FAILED", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(context, "ADDED SUCCESSFUL", Toast.LENGTH_SHORT).show()
            }
        }

        companion object {
            private const val name = "AccountManager.db"
            private const val Database_VERSION = 1
            const val TABLE_NAME = "ACCOUNT_MANAGER"
            const val COLUMN_ID = "accountmanager"
            const val COLUMN_EMAIL = "USER_EMAIL"
            const val COLUMN_PASSWORD = "USER_PASSWORD"
        }
      fun readData(): Cursor? {
        val  query : String = "SELECT * FROM " + TABLE_NAME
        val DB : SQLiteDatabase = this.readableDatabase

          var cursor: Cursor? = null
          if(DB != null){
              cursor = DB.rawQuery(query, null)
          }
          return cursor
      }

    }

注册活动(这里只有我添加电子邮件和密码到Sqlite):

package com.lordshivaproduct.commenting_FROM_SHIVAN

    import adapter.DataBaseHolder
    import android.Manifest
    import android.content.Intent
    import android.content.pm.PackageManager
    import android.net.Uri
    import android.os.Build
    import android.os.Bundle
    import android.view.View
    import android.widget.*
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    import com.google.android.material.snackbar.Snackbar
    import com.google.firebase.auth.FirebaseAuth
    import com.google.firebase.auth.FirebaseUser
    import com.google.firebase.auth.UserProfileChangeRequest
    import com.google.firebase.storage.FirebaseStorage
    import com.google.firebase.storage.StorageReference

    @Suppress("DEPRECATION")
    class Register_user_soma : AppCompatActivity() {
        private lateinit var imgshivprofile : ImageView
        private lateinit var pickedImage: Uri
        private lateinit var userName : EditText
        private lateinit var userEmail : EditText
        private lateinit var userPassword: EditText
        private lateinit var usershivConfirmpassword : EditText
        private lateinit var progresomam : ProgressBar
        private lateinit var Image: ImageView
        private lateinit var rglogsh:TextView

        private lateinit var reg: Button
    //    private
        var PReqCode = 1
        private var REQUESTCODE: Int = 1

        private lateinit var auth: FirebaseAuth
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_register_user_soma)
            supportActionBar?.hide()
            userName = findViewById(R.id.Nameregshiv)
            userEmail = findViewById(R.id.Emailregshiv)
            userPassword = findViewById(R.id.Passwordshiv)
            usershivConfirmpassword = findViewById(R.id.confirmpassword)
            reg = findViewById(R.id.button)
            auth = FirebaseAuth.getInstance()
            imgshivprofile = findViewById(R.id.imageshivprofile)
            Image = findViewById(R.id.imageViewofsh)
            progresomam = findViewById(R.id.progressBarofsomam)
            progresomam.visibility = View.GONE
           val ccountManager:TextView = findViewById(R.id.AccountManager)

            ccountManager.setOnClickListener{
                startActivity(Intent(this, AccountManager::class.java))
            //   val inflater : LayoutInflater = this.getSystemService(this.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                //  val v :View= LayoutInflater.from(this).inflate(R.layout.accountmanagersheet, null,false)
               //   val dialog = BottomSheetDialog(this)
                  
                  
                //  dialog.setContentView(v)
                  //dialog.setCancelable(true)
                //  dialog.show()            
            
                     
                     
            
            }
            
            
            
            rglogsh = findViewById(R.id.loginforsh)
            imgshivprofile.setOnClickListener{
                if(Build.VERSION.SDK_INT >= 22){
                    checkAndRequestForPermission()
                }else {
                    openGallery()
                   }

                }


            rglogsh.setOnClickListener{
                startActivity(Intent(this, Login::class.java))
            }

            reg.setOnClickListener{
                val name = userName.text.toString()
                val email = userEmail.text.toString()
                val pass = userPassword.text.toString()
                val pass2 = usershivConfirmpassword.text.toString()
                reg.visibility = View.GONE
                progresomam.visibility = View.VISIBLE

                if(name.isEmpty() || email.isEmpty() || pass.isEmpty() || pass != pass2 || pickedImage.toString() == null){
                    if(pass.length < 8){
                        createSnackbar( "Password must be greater than 8 characters")
                        progresomam.visibility = View.GONE
                        reg.visibility = View.VISIBLE
                    }
                    createSnackbar("Please verify all fields")
                    progresomam.visibility = View.GONE
                    reg.visibility = View.VISIBLE
                } else{
                    createUserAccount(email, name, pass)
                    Accountanager(email,pass)
                    reg.visibility = View.GONE
                    progresomam.visibility =View.VISIBLE
                }
            }
            }

        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
            if(resultCode == RESULT_OK && requestCode == REQUESTCODE && data != null){
                pickedImage = data.data!!
                imgshivprofile.setImageURI(pickedImage)
                Image.visibility = View.GONE
            }
        }

        private fun createUserAccount(email: String, name: String, pass: String) {
            auth.createUserWithEmailAndPassword(email, pass)
                    .addOnCompleteListener {
                        if(it.isSuccessful){
                            createSnackbar("profile created")
                            updateUserInfo(name, pickedImage, auth.currentUser)
                        } else {
                            it.exception?.message?.let { it1 -> createSnackbar(it1) }
                            reg.visibility = View.VISIBLE
                            progresomam.visibility =View.GONE
                        }
                    }
        }

        private fun Accountanager(email:String,pass:String){
        
            val db : DataBaseHolder = DataBaseHolder(this)
            db.add(email,pass)
        }

         

        private fun updateUserInfo(name: String, pickedImage: Uri, currentUser: FirebaseUser?) {
            val storage: StorageReference = FirebaseStorage.getInstance().reference.child("shiv photos")
            val filePath: StorageReference = storage.child(pickedImage.lastPathSegment.toString())
            filePath.putFile(pickedImage).addOnSuccessListener {
                filePath.downloadUrl.addOnSuccessListener {
                    val profileUpdate: UserProfileChangeRequest = UserProfileChangeRequest.Builder()
                            .setDisplayName(name)
                            .setPhotoUri(it)
                            .build()
                    currentUser!!.updateProfile(profileUpdate).addOnCompleteListener {
                        if(it.isSuccessful){
                            createSnackbar("Register completed")
                            progresomam.visibility = View.GONE
                            startActivity(Intent(this, Onboardingshiva::class.java))
                        }
                    }
                }
            }
        }

        private fun checkAndRequestForPermission() {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    createSnackbar( "Accept for Required Permission")
                } else {
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                            PReqCode)
                }
            } else {
                openGallery()
            }
        }

        private fun openGallery() {
            val galleryintent = Intent(Intent.ACTION_GET_CONTENT)
            galleryintent.type = "image/*"
            startActivityForResult(galleryintent, REQUESTCODE)
        }

        private fun createSnackbar(message: String){
            val regusomam: View = findViewById(R.id.regsiv)
    Snackbar.make(regusomam, message, Snackbar.LENGTH_LONG).show()
}

}
AccountManager(这里只有我从Sqlite获得价值):

package com.lordshivaproduct.commenting_FROM_SHIVAN

    import adapter.DataBaseHolder
    import adapter.accuntmanagerdb
    import android.database.Cursor
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.TextView
    import android.widget.Toast
    import androidx.recyclerview.widget.DividerItemDecoration
    import androidx.recyclerview.widget.LinearLayoutManager
    import androidx.recyclerview.widget.RecyclerView

    class AccountManager : AppCompatActivity() {

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_accountmanager)
        
        
            
            val mydb:DataBaseHolder = DataBaseHolder(this)
            val dbemail : ArrayList<String> = ArrayList()
            val dbpassword:ArrayList<String> = ArrayList()
            
            
                        val  acRecyclerView: RecyclerView = findViewById(R.id.acylerview)
                        acRecyclerView.setHasFixedSize(false)
                        acRecyclerView.addItemDecoration(


                            DividerItemDecoration(
                                this, DividerItemDecoration.VERTICAL
                            )
                        )
                        displaydata(mydb, dbemail, dbpassword)
                        val linearLayoutManager = LinearLayoutManager(this)
                        acRecyclerView.layoutManager = linearLayoutManager
                        val accountmanagerdb = accuntmanagerdb(this,dbemail,dbpassword)
                        acRecyclerView.setAdapter(accountmanagerdb)
                        
                        
        
        
        }
        
        fun displaydata(mydb: DataBaseHolder, dbemail:ArrayList<String>, dbpassword:ArrayList<String>){
            val cursor : Cursor? = mydb.readData()
             if (cursor != null) {
                 if(cursor.count == 0 ){
                     Toast.makeText(this, "No Data", Toast.LENGTH_SHORT).show()
                 }
                 else{
                     while(cursor.moveToNext()){
                          dbemail.add(cursor.getString(0))
                         dbpassword.add(cursor.getString(1))
                     }
                 }
             }
        }
        
        
    }

acccountmanageradapter(适配器类:充气布局)

package adapter

import android.content.Context
import android.content.Intent
import java.util.ArrayList
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import android.view.LayoutInflater
import android.view.View
import com.lordshivaproduct.commenting_FROM_SHIVAN.R
import android.widget.TextView
import com.lordshivaproduct.commenting_FROM_SHIVAN.Login
import com.lordshivaproduct.commenting_FROM_SHIVAN.viewing_post_nama

class accuntmanagerdb internal constructor(
    var context: Context,
    var dbemail: ArrayList<String>,
    var dbpassword: ArrayList<String>
) : RecyclerView.Adapter<accuntmanagerdb.MyViewHolder>() {
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val inflater = LayoutInflater.from(context)
        val view = inflater.inflate(R.layout.accountmanagerui, parent, false)
        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.email.text = dbemail[position].toString()
        holder.password.text = dbpassword[position].toString()
    }

    override fun getItemCount(): Int {
        return 0
    }

    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var email: TextView
        var password: TextView

        init {
            email = itemView.findViewById(R.id.EMAIL)
            password = itemView.findViewById(R.id.PASSWORD)
            itemView.setOnClickListener{
                val intent = Intent(context, Login::class.java)
                val position: Int = adapterPosition
                intent.putExtra("Email", dbemail[position].toString())
                intent.putExtra("Password", dbpassword[position].toString())
                context.startActivity(intent)
            }
        }
    }
}

对不起很多的线,我知道我在这里添加了很多线,但我不知道是什么问题,所以请帮助我解决这个问题
提前感谢

hc2pp10m

hc2pp10m1#

错误发生在适配器accuntmanagerdb中:

override fun getItemCount(): Int {
    return 0
}

你必须在这里返回项目的实际计数,如果你返回0,列表认为它有零个项目。在你的情况下正确的方法是:

override fun getItemCount(): Int {
    return dbemail.size
}

相关问题