Добавление данных во вторую таблицу в SQLite android studio (kotlin) завершается неудачно, если ее код идентичен первой таблице, которая успешно выполняется - PullRequest
0 голосов
/ 27 февраля 2020

Я начинающий, когда дело доходит до кодирования в студии android, но я создаю приложение, в котором есть функция регистрации и входа в систему, после входа в систему пользователь сможет добавлять данные об урожаях

Часть регистрации в приложении работает нормально, это означает, что я могу успешно вставить данные в таблицу моих счетов, но при добавлении данных о посевах происходит сбой. Пожалуйста, помогите спасибо

Код при регистрации

private lateinit var auth: FirebaseAuth

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_signup_form)
    auth = FirebaseAuth.getInstance()



    btn_signUp.setOnClickListener{
        signUpUser()
    }
}

private fun signUpUser(){
    val context = this
    var result = 0
    if(rg_buttons.checkedRadioButtonId != -1){
        if(rb_Producer.isChecked)
            result = 1
        if(rb_Consumer.isChecked)
            result = 2
        if(rb_Transport.isChecked)
            result = 3
    }
    if(ePassword.text.toString() == eCPassword.text.toString()){
        if(eFname.text.toString().isEmpty()) {
            eFname.error = "Please enter Full Name"
            eFname.requestFocus()
            return
        }
        if(eUname.text.toString().isEmpty()) {
            eUname.error = "Please enter Uname"
            eUname.requestFocus()
            return
        }
        if(eEmail.text.toString().isEmpty()) {
            eEmail.error = "Please enter Email Address"
            eEmail.requestFocus()
            return
        }
        if(!Patterns.EMAIL_ADDRESS.matcher(eEmail.text.toString()).matches()){
            eEmail.error = "Please enter Valid Email Address"
            eEmail.requestFocus()
            return
        }
        if(ePassword.text.toString().isEmpty()) {
            ePassword.error = "Please Enter Password"
            ePassword.requestFocus()
            return
        }
        if(eCPassword.text.toString().isEmpty()) {
            eCPassword.error = "Please Enter Password"
            eCPassword.requestFocus()
            return
        }
        if(ePassword.text.toString().length<6) {
            ePassword.error = "Password must have more than 5 characters"
            ePassword.requestFocus()
            return
        }
    }else{
        eCPassword.error = "Passwords do not Match"
        eCPassword.requestFocus()
        ePassword.error = "Passwords do not Match"
        eEmail.requestFocus()
    }

    auth.createUserWithEmailAndPassword(eEmail.text.toString(), ePassword.text.toString())
        .addOnCompleteListener(this) {task ->
            if (task.isSuccessful) {
                var account = Account(eFname.text.toString(),
                    eUname.text.toString(),
                    eEmail.text.toString(),
                    ePassword.text.toString(),
                    result)
                var db = DataBaseHandler(context)
                db.insertData(account)
                startActivity(Intent(context,MainActivity::class.java))
                finish()
            } else {
                Toast.makeText(baseContext,"Sign up Failed.",Toast.LENGTH_SHORT).show()
            }

        }
}

Код для добавления данных по культурам

class AddProductActivity : AppCompatActivity(){

override fun onCreate(savedInstanceState: Bundle?){
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_addproduct)

    btn_AddProd.setOnClickListener{
        addProduct()
    }
}

private fun addProduct(){
    val dbManager = DataBaseHandler(this)
    val email = intent.getStringExtra("EXTRA_EMAIL")
    val account = dbManager.getID(email!!)
        var crop = Crop(eProdName.text.toString(),
            eProdPrice.text.toString().toInt(),
            eProdDetails.text.toString(),
            eProdDate.text.toString())
        dbManager.insertData2(crop)
        startActivity(Intent(this,ProducerFeedActivity::class.java))
        finish()
}
}

класс конструктора для учетной записи:

class Account{
var id : Int = 0
var fname : String = ""
var uname : String = ""
var password : String = ""
var email : String = ""
var type : Int = 0

constructor(fname:String,uname:String,email:String,password:String,type:Int){
    this.uname = uname
    this.fname = fname
    this.email = email
    this.password = password
    this.type = type
}
constructor()
}

класс конструктора для Crop:

class Crop{
var id : Int = 0
var oid : Int = 0
var cname : String = ""
var cprice : Int = 0
var cdetails : String = ""
var cdate : String = ""


constructor(cname:String,cprice:Int,cdetails:String,cdate:String){
    this.cname = cname
    this.cprice = cprice
    this.cdetails = cdetails
    this.cdate = cdate
}
}

класс Databasehelper:

package com.example.myapplication

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

const val DATABASE_NAME = "MyDB"

const val TABLE_NAME = "Account"
const val COL_FNAME = "fname"
const val COL_UNAME = "uname"
const val COL_PASSWORD = "password"
const val COL_EMAIL = "email"
const val COL_ID = "id"
const val COL_TYPE = "type"

const val TABLE_NAME2 = "Crop"
const val COL_CID = "id"
const val COL_OID = "oid"
const val COL_CNAME = "cname"
const val COL_CPRICE = "cprice"
const val COL_CDETAILS = "cdetails"
const val COL_CDATE = "cdate"

class DataBaseHandler (var context: Context) : SQLiteOpenHelper(context, DATABASE_NAME,null,1){
    override fun onCreate(db: SQLiteDatabase?) {
        val createTable = "CREATE TABLE " + TABLE_NAME + " (" +
                COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                COL_FNAME + " VARCHAR(256)," +
                COL_UNAME + " VARCHAR(256)," +
                COL_EMAIL + " VARCHAR(256)," +
                COL_PASSWORD + " VARCHAR(256)," +
                COL_TYPE + " INTEGER(1))"
        val createTable2 = "CREATE TABLE " + TABLE_NAME2 + " (" +
                COL_CID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                COL_CNAME + " VARCHAR(256)," +
                COL_CPRICE + " INTEGER(4)," +
                COL_CDETAILS + " VARCHAR(256)," +
                COL_CDATE + " VARCHAR(256))"

        db?.execSQL(createTable)
        db?.execSQL(createTable2)
    }

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.

}

fun insertData(account: Account){
    val db = this.writableDatabase
    val cv = ContentValues()
    cv.put(COL_FNAME,account.fname)
    cv.put(COL_UNAME,account.uname)
    cv.put(COL_EMAIL,account.email)
    cv.put(COL_PASSWORD,account.password)
    cv.put(COL_TYPE,account.type)
    val result = db.insert(TABLE_NAME,null,cv)
    if(result == (-1).toLong())
        Toast.makeText(context, "Failed",Toast.LENGTH_SHORT).show()
    else
        Toast.makeText(context, "Success",Toast.LENGTH_SHORT).show()
}

fun insertData2(crop: Crop){
    val db2 = this.writableDatabase
    val cv2 = ContentValues()
    cv2.put(COL_CNAME,crop.cname)
    cv2.put(COL_CPRICE,crop.cprice)
    cv2.put(COL_CDETAILS,crop.cdetails)
    cv2.put(COL_CDATE,crop.cdate)
    val result2 = db2.insert(TABLE_NAME2,null,cv2)
    if(result2 == (-1).toLong())
        Toast.makeText(context, "Failed",Toast.LENGTH_SHORT).show()
    else
        Toast.makeText(context, "Success",Toast.LENGTH_SHORT).show()
}

fun getType(email: String): Account? {
    val db = this.writableDatabase
    val selectQuery = "SELECT  * FROM $TABLE_NAME WHERE $COL_EMAIL = ?"
        db.rawQuery(selectQuery, arrayOf(email)).use { // .use requires API 16
        if (it.moveToFirst()) {
            val result = Account()
            result.type = it.getInt(it.getColumnIndex(COL_TYPE))
            result.email = it.getString(it.getColumnIndex(COL_EMAIL))
            return result
        }
    }
    return null
}

fun getID(email: String): Account? {
    val db = this.writableDatabase
    val selectQuery = "SELECT  * FROM $TABLE_NAME WHERE $COL_EMAIL = ?"
    db.rawQuery(selectQuery, arrayOf(email)).use { // .use requires API 16
        if (it.moveToFirst()) {
            val result = Account()
            result.id = it.getInt(it.getColumnIndex(COL_ID))
            result.email = it.getString(it.getColumnIndex(COL_EMAIL))
            return result
        }
    }
    return null
}

fun getFname(email: String): Account? {
    val db = this.writableDatabase
    val selectQuery = "SELECT  * FROM $TABLE_NAME WHERE $COL_EMAIL = ?"
    db.rawQuery(selectQuery, arrayOf(email)).use {
        // .use requires API 16
        if (it.moveToFirst()) {
            val result = Account()
            result.fname = it.getString(it.getColumnIndex(COL_FNAME))
            result.email = it.getString(it.getColumnIndex(COL_EMAIL))
            return result
        }
    }
    return null
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...