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

huangapple go评论64阅读模式
英文:

Not Inflating Layout While Retrieving From Sqlite Database In Kotlin

问题

I understand that you'd like me to translate the code-related portions of your text. Here is the translated code:

我正在处理一个功能即当用户注册他们的电子邮件和密码时将其保存在SQLite中并可以在名为Account Manager的活动中检索
我正在使用Kotlin进行编码我只是根据SQLite中的数据膨胀布局
电子邮件和密码已成功添加但在RecyclerView中不工作的布局膨胀布局未膨胀PFB的屏幕截图[未膨胀布局的活动][1]

我的DataBaseHolder类

```kotlin
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
    }
}

这只是代码的一部分,如果您需要进一步的翻译,请告诉我。

英文:

I am working with one feature which is while user register their Email and password that will be saved in sqlite and can be retrieved in activity Named Account Manager.
I am using kotlin for coding and I just inflate layout according to data in sqlite. Email and password added successfully but the layout inflating not working in Recycler View. The layout doesn't inflated. PFB the screen shot Activity Without Layout Inflated

My DataBaseHolder Class :

		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
}
}

Register Activity(Here Only I add Email And Password To 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(Here Only I am Getting value from 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(Adapter Class: Inflating Layout)

	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)
}
}
}
}

Sorry For Lot's Of Line, I know i added lot of lines here but I dont know what is the issue so please help me solve this

Thanks In Advance

答案1

得分: 0

The error is within your Adapter accuntmanagerdb:

override fun getItemCount(): Int {
return 0
}

You must return the actual count of the items here, if you return 0 the list thinks it has zero items.
Correct way in your case would be:

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

The error is within your Adapter accuntmanagerdb:

override fun getItemCount(): Int {
return 0
}

You must return the acutal count of the items here, if you return 0 the list thinks it has zero items.
Correct way in your case would be:

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

huangapple
  • 本文由 发表于 2023年5月11日 15:49:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76225241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定