Kotlin entered value not searching database - validation

We have worked on this code to error trap a value entered in a Edit Text field
When the value is entered correctly we are informed that the entered value does not match
BUT if we select the value from a recycler view list and populate the Edit Text field with the value the search tells us we have a match
Here is the code for the search in the DBHelper
fun getOneName(id: Int): Contact? {
val db = this.writableDatabase
val selectQuery = "SELECT * FROM $TABLE_NAME WHERE $colId = ?"
db.rawQuery(selectQuery, arrayOf(id.toString())).use { // .use requires API 16
if (it.moveToFirst()) {
val result = Contact(id = 0,name ="")
result.id = it.getInt(it.getColumnIndex(colId))
result.name = it.getString(it.getColumnIndex(colName))
return result
}
}
return null
}
We used this for the Model Class our first time using data class as just plain class
data class Contact (
var id: Int,
var name: String
)
And here is the button click that manages the search
btnGetID.setOnClickListener {
if(etPerson.text.toString().trim().isNullOrEmpty()){
message("Enter Contact Name")
return#setOnClickListener
}
var numeric = true
var string = etPerson.text.toString().trim()
numeric = string.matches(".*\\d+.*".toRegex())
if(numeric){
message("No NUMBERS")
return#setOnClickListener
}
val dbManager = DBHelper(this)
var name = etPerson.text.toString()
//val contact = dbManager.getOneName(name)
val contact = dbManager.getOneName(id.toInt())
if(contact?.name.equals(name)){
println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contact ID= "+contact)
etPerson.setText("The contact name is $name the ID is "+contact?.id.toString())
}else{
etPerson.setText("Name NOT = to $name and the ID is "+contact?.id.toString())
}
}
We know the name Sally is in the DB if we type Sally in the else statement shows Name NOT = bla
If we select Sally from the Recyclerview List the first statement shows The contact name bla bla
Kotlin 1.2.71 API 27
Our question is why is the hand typed name failing if it mataches?
HERE IS THE CORRECT CODE FOR THE DBHelper
fun getOneName(name: String): Contact? {
val db = this.writableDatabase
val selectQuery = "SELECT * FROM $TABLE_NAME WHERE $colName = ?"
db.rawQuery(selectQuery, arrayOf(name)).use { // .use requires API 16
if (it.moveToFirst()) {
val result = Contact(id = 0,name ="")
result.id = it.getInt(it.getColumnIndex(colId))
result.name = it.getString(it.getColumnIndex(colName))
return result
}
}
return null
}

Related

Kotlin MVVM, How to get the latest value from Entity in ViewModel?

I have created an app where I try to insert a record with the latest order number increased by one.
The main function is triggered from Activity, however, the whole process is in my ViewModel.
Issue no 1, After I insert a new record the order by number is not updated.
Issue no 2, When I insert first record the order by number is null, for that reason I am checking for null and setting the value to 0.
My goal here is to get the latest order_by number from Entity in my ViewModel, increased by 1 and add that new number to my new record using fun addTestData(..).
Entity:
#Entity(tableName = "word_table")
data class Word(
#ColumnInfo(name = "id") val id: Int,
#ColumnInfo(name = "word") val word: String,
#ColumnInfo(name = "order_by") val orderBy: Int
Dao:
#Query("SELECT order_by FROM word_table ORDER BY order_by DESC LIMIT 1")
suspend fun getHighestOrderId(): Int
Repository:
#Suppress("RedundantSuspendModifier")
#WorkerThread
suspend fun getHighestOrderId(): Int {
return wordDao.getHighestOrderId()
}
ViewModel:
private var _highestOrderId = MutableLiveData<Int>()
val highestOrderId: LiveData<Int> = _highestOrderId
fun getHighestOrderId() = viewModelScope.launch {
val highestOrderId = repository.getHighestOrderId()
_highestOrderId.postValue(highestOrderId)
}
fun addTestData(text: String) {
for (i in 0..1500) {
getHighestOrderId()
var highestNo = 0
val highestOrderId = highestOrderId.value
if (highestOrderId == null) {
highestNo = 0
} else {
highestNo = highestOrderId
}
val addNumber = highestNo + 1
val word2 = Word(0, text + "_" + addNumber,addNumber)
insertWord(word2)
}
}
Activity:
wordViewModel.addTestData(text)

How can I retrieve Id of inserted entity using Entity framework Core?

I have a concern since as I am new to using EntityFramework Core, that if I add an object, that I still do not have the id generated by the database, sending the object to it in the transaction, I would add it automatically, this is my code ,
public async Task<ServiceResult<Common.Entities.Company>> SaveCompany(Domain.Models.Company companyModel, Domain.Models.Administrator administratoModel)
{
ServiceResult<Common.Entities.Company> serviceResult = new ServiceResult<Common.Entities.Company>();
try
{
if (user == null && companyExistsRnc == false)
{
Common.Entities.Company myCompany = new Common.Entities.Company
{
CompanyId = companyModel.CompanyId, // The id has not been generated yet,
CompanyName = companyModel.CompanyName,
Rnc = companyModel.Rnc,
CountryId = companyModel.Country.CountryId,
Telephone = companyModel.Telephone,
PersonContact = companyModel.PersonContact,
Address = companyModel.Address,
PhotoPath = companyModel.PhotoPath,
IsActive = false,
};
await _companyRepository.SaveCompany(myCompany); // this is the method that I add the company object to the database and do the savechanges
Common.Entities.User myUser = new Common.Entities.User
{
FirstName = administratoModel.FirstName,
SecondName = administratoModel.SecondName,
FirstLastName = administratoModel.FirstLastName,
SecondLastName = administratoModel.SecondLastName,
GenderId = administratoModel.Gender.GenderId,
PhoneNumber = administratoModel.Telephone,
Email = administratoModel.Email,
UserName = administratoModel.Email,
IsActive = administratoModel.IsActive,
UserTypeId = (short)Common.Core.UserType.Administrator,
Company = myCompany, // here I send the my company object for when I do the savechanges, I think it will add it to me
};
await _userHelper.AddUserAsync(myUser, administratoModel.Password);
await _userHelper.AddUserToRoleAsync(myUser, Common.Core.UserType.Administrator.ToString());
Common.Entities.Administrator myAdministrator = new Common.Entities.Administrator
{
AdministratorId = administratoModel.AdministratorId,
FirstName = administratoModel.FirstName,
SecondName = administratoModel.SecondName,
FirstLastName = administratoModel.FirstLastName,
SecondLastName = administratoModel.SecondLastName,
GenderId = administratoModel.Gender.GenderId,
Email = administratoModel.Email,
Telephone = administratoModel.Telephone,
IsActive = true,
PhotoPath = administratoModel.PhotoPath,
UserTypeId = (short)Common.Core.UserType.Administrator,
Company = myCompany, // company object without the id
User = myUser, // user object without the id
};
await _administratorRepository.SaveAdministrator(myAdministrator);
serviceResult.Data = myCompany;
serviceResult.Message = "CompaƱia agregada!";
}
}
I am new to using entity framework core, and if in case I am wrong in what I am doing please indicate in which part I am doing it wrong, to correct, I await your comments and would appreciate the help,

Pass multiple Filters to Android Room Dao SQL Query from ViewModel with Repository

I am using the below to fetch Database rows to my Adapter, however I want to return rows from multi-filtered single query using either "LIKE" and/or "WHERE" and basically all sql query filter types, I can do one filter via MutableLiveData<String>();
end result would be like ...
#Query("SELECT * FROM mytable WHERE suburb LIKE '%' || :suburb || '%' postcode LIKE '%' || :postcode || '%' BETWEEN firstDate AND lastDate")
fun getFilteredRows(
suburb: String?,
postcode: String?,
firstDate: String?,
lastDate: String?): LiveData<List<MyTable>>
As per below, currently way only can pass one filter var.
ViewModel Class
class MyViewModel internal constructor(repository: MyRepository) : ViewModel()
//filter by suburb
var suburb = MutableLiveData<String>().apply {
//do I set as HashMap??
value = SUBURB
}
//LiveData Observer access
val filteredRows: LiveData<List<MyTable>> = suburb.switchMap {
//pass multiple filters to repository here
//but currently only can pass one string to repository
repository.getFilteredRows(it)
}
//MyViewModel function to set the suburb value
fun setSuburb(_suburb: String) {
suburb.value = _suburb
}
//companion object
companion object {
var SUBURB: String? = null
}
Repository Class
class Repository private constructor(private val dao: Dao)
//basic repo to dao communtication
fun getFilteredRows(suburb: String?) = dao.getFilteredRows(suburb)
Dao Interface
#Dao
interface Dao
//here I want to receive multiple Strings to do filtering within the query
#Query("SELECT * FROM mytable WHERE suburb LIKE '%' || :suburb || '%'")
fun getFilteredRows(suburb: String?): LiveData<List<MyTable>>
I have tried with passing basic var Strings with no luck, seems only MutableLiveData is the way to pass variable to the Dao via ViewModel & Repository
** See Edit Below **
Not ideal to say the least, actually would not recommend, however, current work around is to "loop" through multiple MutableLiveData variables
ViewModel Class
var suburb = MutableLiveData<String>().apply { value = SUBURB }
var postcode = MutableLiveData<String>().apply { value = POSTCODE }
var limit = MutableLiveData<Int>().apply { value = LIMIT }
val filteredRows: LiveData<List<MyTable>> =
suburb.switchMap {
//set suburb MutableLiveData
var suburb = it
postcode.switchMap {
//set postcode MutableLiveData
var postcode = it
}
limit.switchMap {
//set limit MutableLiveData
var limit = it
}
repository.getFilteredRows(suburb, postcode, limit)
}
/// EDIT ANSWER ///
Using HashMap to pass multiple filters (Strings) to Dao SQl Query.
Tested a returned what was expected, so confirming this works.
Foreseeable issue is when needing to pass Strings & Int etc, may have to refer back to passing as Strings only & then do parse.ToInt() etc on Int String Values
build HashMap in my Fragment to pass to MyViewModel
lateinit var myModel: LiveData<MyTable>
var filters = HashMap<String, String>()
filters.put("suburb", myModel.value!!.suburb)
filters.put("postcode", myModel.value!!.postcode)
with(viewModel) {
//pass my HashMap to my ViewModel for update/change/set on filters MutableLiveData HashMap variable
setFilters(filters)
}
MyViewModel Class
//initilise filters MutableLiveData HashMap variable
var filters = MutableLiveData<HashMap<String, String>>().apply { value = FILTERS }
//function to update/change/set filters MutableLiveData HashMap variable
//see setFilters(filters) used in above Fragment
fun setFilters(_filters: HashMap<String, String>) {
filters.value = _filters
}
//foreach on passed HashMap via switchMap{}
val filtered: LiveData<List<MyTable>> = filters.switchMap {
//initilise variables
var suburb = ""
var postcode = ""
//foreach loop on HashCookie :)
for (filter in it) {
if(filter.key.equals("suburb")){
suburb = filter.value
}else if(filter.key.equals("postcode")) {
postcode = filter.value
}
}
//pass strings to Dao
repository.getFiltered(suburb, postcode)
}
//companion object
companion object {
var FILTERS: HashMap<String, String>? = null
}
Repository Class
//send variables to the Dao Interface
fun getFiltered(suburb: String?, postcode: String?) = dao.getFiltered(suburb, postcode)
Dao Interface
#Query("SELECT * FROM mytable WHERE suburb LIKE '%' || :suburb || '%' AND postcode LIKE '%' || :postcode || '%' ")
fun getFiltered(suburb: String?, postcode: String?): LiveData<List<MyTable>>

How to call Expression Func with two input parameters

I have following Expression Func which is receiving two input paramters, first is Person Object, second is bool and returning another type of Object PersonProfile
private Exression<Func<Person, bool, PersonProfile>> PersonProfileProjection => (person, isValid) =>
new PersonProfile
{
FirstName = person.FirstName,
HasAddress = isValid ? person.Address1 : null
};
And I am trying to call this while fetching Person table from dbContext.
_dbContext.Persons.Select(PersonProfileProjection);
I am confused how to send boolean parameter inside PersonProfileProjection. It works when I only put one input and one output parameter like this. But I want extra boolean input as well.
Any help would be highly appreciated.
You can follow Microsoft documentation for this : Expression Class
One sample created for SQLite that show above function usage.
public void GetData()
{
var connection = new SQLiteConnection(#"Data Source=database.sqlite;Version=3;");
var context = new DataContext(connection);
connection.Open();
var createtableQuery = #"
drop table Company;
CREATE TABLE[Company]
(
[ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
[Seats] INTEGER NOT NULL
);
";
var command = new SQLiteCommand(createtableQuery, connection);
command.ExecuteNonQuery();
Company com = new Company()
{
Id = 6,
Seats = 7
};
context.GetTable<Company>().InsertOnSubmit(com);
context.SubmitChanges();
var companies = context.GetTable<Company>();
foreach (var company in companies)
{
Console.WriteLine("Company: {0} {1}",
company.Id, company.Seats);
}
//compile Expression using Compile method to invoke it as Delegate
Func<int,int, Company> PersonProfileProjectionComp = PersonProfileProjection.Compile();
var dd = companies.Select(p => PersonProfileProjectionComp(p.Id,p.Seats));
//// Below line inline use. Both works.
//var dd = companies.Select(p => PersonProfileProjection.Compile().Invoke(p.Id,p.Seats));
}
private System.Linq.Expressions.Expression<Func<int, int, Company>> PersonProfileProjection => (person, seats) =>
new Company
{
Id = person,
Seats = seats
};
or in one line use this :
PersonProfileProjection.Compile().Invoke(person, isValid)
You could declare it as a Func instead of an expression:
private Func<Person, bool, PersonProfile> PersonProfileProjection => (person, isValid) =>
new PersonProfile
{
FirstName = person.FirstName,
HasAddress = isValid // do what you meant to do
};
... and call it as:
_dbContext.Persons.Select(p => PersonProfileProjection(p, true));
You could as well write an ordinary method:
private PersonProfile PersonProfileProjection(Person person, bool isValid)
{
return new PersonProfile
{
FirstName = person.FirstName,
HasAddress = isValid // do what you want to do
};
}
...and call it the same way:
_dbContext.Persons.Select(p => PersonProfileProjection(p, true));

Entity Framework cycle of data

I have an Account object, which has many Transactions related to it.
In one method, I get all transactions for a particular account.
var transactionlines = (from p in Context.account_transaction
.Include("account_transaction_line")
// .Include("Account")
.Include("account.z_account_type")
.Include("account.institution")
.Include("third_party")
.Include("third_party.z_third_party_type")
.Include("z_account_transaction_type")
.Include("account_transaction_line.transaction_sub_category")
.Include("account_transaction_line.transaction_sub_category.transaction_category")
.Include("z_account_transaction_entry_type")
.Include("account_transaction_line.cost_centre")
where p.account_id == accountId
&& p.deleted == null
select p).ToList();
This is meant to return me a list of transactions, with their related objects. I then pass each object to a Translator, which translates them into data transfer objects, which are then passed back to my main application.
public TransactionDto TranslateTransaction(account_transaction source)
{
LogUserActivity("in TranslateTransaction");
var result = new TransactionDto
{
Id = source.id,
Version = source.version,
AccountId = source.account_id,
// Account = TranslateAccount(source.account, false),
ThirdPartyId = source.third_party_id,
ThirdParty = TranslateThirdParty(source.third_party),
Amount = source.transaction_amount,
EntryTypeId = source.account_transaction_entry_type_id,
EntryType = new ReferenceItemDto
{
Id = source.account_transaction_entry_type_id,
Description = source.z_account_transaction_entry_type.description,
Deleted = source.z_account_transaction_entry_type.deleted != null
},
Notes = source.notes,
TransactionDate = source.transaction_date,
TransactionTypeId = source.account_transaction_type_id,
TransactionType = new ReferenceItemDto
{
Id = source.z_account_transaction_type.id,
Description = source.z_account_transaction_type.description,
Deleted = source.z_account_transaction_type.deleted != null
}
};
... return my object
}
The problem is:
An account has Transactions, and a Transaction therefore belongs to an Account. It seems my translators are being called way too much, and reloading a lot of data because of this.
When I load my transaction object, it's 'account' property has a'transactions' propery, which has a list of all the transactions associated to that account. Each transaction then has an account property... and those account peroprties again, have a list of all the transactions... and on and on it goes.
Is there a way I can limit the loading to one level or something?
I have this set:
Context.Configuration.LazyLoadingEnabled = false;
I was hoping my 'Includes' would be all that is loaded... Don't load 'un-included' related data?
As requested, here is my TranslateAccount method:
public AccountDto TranslateAccount(account p, bool includeCardsInterestRateDataAndBalance)
{
LogUserActivity("in TranslateAccount");
if (p == null)
return null;
var result =
new AccountDto
{
Id = p.id,
Description = p.description,
PortfolioId = p.institution.account_portfolio_id,
AccountNumber = p.account_number,
Institution = TranslateInstitution(p.institution),
AccountType = new ReferenceItemDto
{
Id = p.account_type_id,
Description = p.z_account_type.description
},
AccountTypeId = p.account_type_id,
InstitutionId = p.institution_id,
MinimumBalance = p.min_balance,
OpeningBalance = p.opening_balance,
OpeningDate = p.opening_date
};
if (includeCardsInterestRateDataAndBalance)
{
// Add the assigned cards collection
foreach (var card in p.account_card)
{
result.Cards.Add(new AccountCardDto
{
Id = card.id,
AccountId = card.account_id,
Active = card.active,
CardHolderName = card.card_holder_name,
CardNumber = card.card_number,
ExpiryDate = card.expiry
});
}
// Populate the current interest rate
result.CurrentRate = GetCurrentInterestRate(result.Id);
// Add all rates to the account
foreach (var rate in p.account_rate)
{
result.Rates.Add(
new AccountRateDto
{
Id = rate.id,
Description = rate.description,
Deleted = rate.deleted != null,
AccountId = rate.account_id,
EndDate = rate.end_date,
Rate = rate.rate,
StartDate = rate.start_date
});
}
result.CurrentBalance = CurrentBalance(result.Id);
}
LogUserActivity("out TranslateAccount");
return result;
}
The entity framework context maintains a cache of data that has been pulled out of the database. Regardless of lazy loading being enabled/disabled, you can call Transaction.Account.Transactions[0].Account.Transactions[0]... as much as you want without loading anything else from the database.
The problem is not in the cyclical nature of entity framework objects - it is somewhere in the logic of your translation objects.

Resources