How to fix this problem in UnitTests Kotlin firebase? - firebase

I have a problem with this test code:
package mainPackage.tests
import com.google.firebase.firestore.FirebaseFirestore
import mainPackage.model.RepositoryMockup
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
class RepositoryTest {
#Test
fun testWriteNewUser() {
val repository = RepositoryMockup()
val email = "test.first#pwr.edu.pl"
val pass = "testpassword123"
val isATeacher = true
val task = repository.writeNewUser(pass, email, isATeacher)
task.addOnCompleteListener {
assertTrue(it.isSuccessful)
}
}
}
Here is an error:
And here is a class that I am testing:
package mainPackage.model
import com.google.firebase.firestore.FirebaseFirestore
import android.util.Log
import com.google.android.gms.tasks.Task
import com.google.firebase.firestore.FirebaseFirestoreException
import mainPackage.utils.Checks
const val TAG = "FIRESTORE"
class RepositoryMockup {
//--------------------------------
//Firebase functions
fun writeNewUser(pass: String, email: String, isATeacher: Boolean?) : Task<Void> {
val database = FirebaseFirestore.getInstance()
val myRef = database.collection("Users").document(email)
val newUser = hashMapOf(
"is_a_teacher" to isATeacher,
"pass" to pass
)
myRef.set(newUser)
.addOnSuccessListener { Log.d(TAG, "User successfully added") }
.addOnFailureListener { e -> Log.w(TAG, "Error writing user", e) }
return myRef.set(newUser)
}
}
It's only a small part of it. I hve tried a lot of things but they didn't help me.
I always got an error.
This class works perfect so the firebase was added correct.
Help me to fix this error.

Related

Default FirebaseApp is not initialized in this process ... Make sure to call FirebaseApp.initializeApp(Context) first

I am trying to add data to firestore. and also i want to do this using dagger. but i keep getting this error. can you help me please......
** Default FirebaseApp is not initialized in this process com.example.vvvv. Make sure to call FirebaseApp.initializeApp(Context) first. **
FirestoreREpository
class FirestoreRepository #Inject constructor(private val usersRef:
CollectionReference) {
fun saveSearchResults(userEntities: List<UserEntity>) {
usersRef.add(userEntities).addOnCompleteListener { task ->
when (task.isSuccessful) {
true -> Log.d(ContentValues.TAG, "added:success")
false -> Log.d(ContentValues.TAG, "added:unsuccess")
}
}
}
}
ViewModel
#HiltViewModel
class UserListViewModel #Inject constructor(private val repository: RoomRepository, private
val firestoreRepository: FirestoreRepository) :
ViewModel() {
private val _users = MutableLiveData<List<User>>()
val users: LiveData<List<User>>
get() = _users
var userData: MutableLiveData<List<User>> = MutableLiveData()
fun userSearch(term: String) {
viewModelScope.launch {
loadFromCache(term)
val getPropertiesDeferred =
GithubApi.retrofitService.searchUser(term)
try {
val userEntities: MutableList<UserEntity> = mutableListOf()
val result = getPropertiesDeferred.body()
_users.value = result?.users
result?.users?.forEach {
userEntities.add(
UserEntity(
term = term,
login = it.login,
avatar_url = it.avatar_url
)
)
}
clearSearchResults(term)
updateSearchResults(userEntities, term)
firestoreRepository.saveSearchResults(userEntities) //save
data with firebase
} catch (e: Exception) {
Log.e("userListErr", e.message.toString())
}
}
}
private fun updateSearchResults(userEntities: List<UserEntity>, term:
String) {
viewModelScope.launch(Dispatchers.IO) {
repository.insertSearchResults(userEntities)
loadFromCache(term)
}
}
private fun loadFromCache(term: String) {
viewModelScope.launch(Dispatchers.IO) {
val list = repository.getSearchResults(term)
userData.postValue(list)
}
}
private fun clearSearchResults(term: String) {
viewModelScope.launch(Dispatchers.IO) {
repository.deleteSearchResults(term)
}
}
}
AppModule
#Module
#InstallIn(SingletonComponent::class)
object APPModule {
#Singleton
#Provides
fun getAppDB(context: Application): AppDatabase {
return AppDatabase.getAppDB(context)
}
#Singleton
#Provides
fun getDao(appDB: AppDatabase): AppDao {
return appDB.getDAO()
}
#Provides
fun provideFirebaseFirestore() = FirebaseFirestore.getInstance()
#Provides
fun provideUsersRef(db: FirebaseFirestore) = db.collection("users")
}
I used multi-module in this project. id com.google.gms.google-services to app directory and solved.
In build.gradle(project) in dependencies add the following:
classpath 'com.google.gms:google-services:4.3.5'
In build.gradle(module) add the following:
plugins {
id 'com.google.gms.google-services'
}
in your last line of code add the following:
apply plugin: 'com.google.gms.google-services'
I meet this problem, because google-service sdk version not work with gradle version.
Maybe you can try with this direction.
The original project build.gradle config is ok.
buildscript {
dependencies {
classpath "com.android.tools.build:gradle:3.2.1"
classpath 'com.google.gms:google-services:4.1.0'
Finally, it's solve by find compatible SDK version.
buildscript {
dependencies {
classpath "com.android.tools.build:gradle:3.3.3"
classpath 'com.google.gms:google-services:4.2.0'

How to pass my viewmodel to a class that does not extend activity

How to pass my viewmodel to a class that does not extend activity
I'm calling my viewmodel like this:
in my EntryAbstract class
where am I going wrong
val FrutasViewModel = ViewModelProvider.NewInstanceFactory().create(FrutasViewModel::class.java)
FrutasViewModel.frutaData.value.forEach { item->
itens.add(ShoppingCart
(id=item.id,photo=item.photo,
name=item.name,quantidade=item.quantidade
,categoria = item.categoria,descricao = item.descricao
,unidade=item.unidade,kilo = item.kilo
))
}
my viewmodel:
package com.example.quitanda.models
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class FrutasViewModel(
private val frutasServices: Services,
):ViewModel() {
private val _frutasData: MutableStateFlow<List<ShoppingCart>> = MutableStateFlow<List<ShoppingCart>>(listOf<ShoppingCart>(ShoppingCart()))
val frutaData: StateFlow<List<ShoppingCart>>
get() = _frutasData
fun getFrutas(){
viewModelScope.launch {
try {
val frutas = frutasServices.getFruta()
_frutasData.value = frutas
}catch (e:Exception){
Log.d("Service error",e.toString())
}
}
}
}
My service:
package com.example.quitanda.models
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
interface Services {
#GET("/category/7")
suspend fun getFruta(
//#Query("apikey")
//apikey:String = "333b4285"
): List<ShoppingCart>
}
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("http://localhost:4000/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
val frutasServices: Services = retrofit.create(Services::class.java)
My model:
package com.example.quitanda.models
import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.parcelize.Parcelize
#Parcelize
data class ShoppingCart(
var count:Int=0,
#field:Json(name="product_title")
var name:String="",
#field:Json(name="product_id")
var id:Int=0,
#field:Json(name="photo_photo")
var photo:String="",
#field:Json(name="product_quant")
var quantidade:Int=0,
#field:Json(name="category_name")
var categoria:String="",
#field:Json(name="product_description")
var descricao:String="",
#field:Json(name="product_price_un")
var unidade:String="",
#field:Json(name="product_price_kg")
var kilo:String="",
var tipos:String=""): Parcelable
When I try to run my code it gives the following error
Does anyone have any idea how to fix this
who can help I am grateful
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quitanda, PID: 11031
java.lang.RuntimeException: Cannot create an instance of class com.example.quitanda.models.FrutasViewModel
I wouldn't recommend doing what you're trying to achieve, because what Android did, is that they've abstracted how viewmodels are scoped, to give you developers the power to easily handle things like orientation-change.
In practice this means, that android views, such as Activity/Fragment implement a ViewModelStoreOwner which contains a ViewModelStore, which handles the scoping and retrieves the correct ViewModel instance based on context.
TL;DR: If you want an android arch.viewmodel then create it in your Activity/Fragment and pass it to the EntryAbstract, though chances are you just need some of the data, which could be set individually for better separation of concerns

Opening SQLite database in Android Studio Kotlin

I'm very new to Kotlin so please bear with me. I want to open a SQLite database or create it if it doesn't exist yet. Afterwards I'd run the appropriate statements to make a table, etc. I'm trying to use SQLiteDatabase. The line of code I'm trying is:
val db = SQLiteDatabase.openOrCreateDatabase("database.db",null, SQLiteDatabase.OPEN_READWRITE)
I get this runtime error when I try the app:
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 1294 SQLITE_CANTOPEN_ENOENT[1294]): Could not open database
I'm not picky about the database, I just want an easy way to read and write to one from within my function.
This is the surrounding code:
package com.google.firebase.codelab.barcode_scanning
// Date/time formatting functions
import android.database.sqlite.SQLiteDatabase
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_row.view.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class QrCodeAdapter(private val qrList: ArrayList<QrCode>) : RecyclerView.Adapter<QrCodeAdapter.QrHolder>() {
//
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QrHolder {
return QrHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_row, parent, false))
}
override fun getItemCount() = qrList.size
override fun onBindViewHolder(holder: QrHolder, position: Int) {
//internal var dbHelper = DatabaseHelper(this)
with(qrList[position]) {
var objname = "Barcode Not Found"
var statustext = ""
// status: 0 = no record, 1 = dirty, 2 = clean, 3 = dwell, 4: dwell done
var status = 0
var lastcleaned = ""
// objcategory: 0 = no record, 1 = contact object, 2 = dwell item
var objcategory = 0
var objcategorytext = ""
// initial setup of current date/time
var unixtime = System.currentTimeMillis()
var currenttime = LocalDateTime.now()
var timeformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
var testtime = currenttime.format(timeformat).toString()
//val db = SQLiteDatabase.openDatabase("//app/maindb.db", null, 0);
val db = SQLiteDatabase.openOrCreateDatabase("database.db",null, null)
//val sql = "SELECT COUNT(*) FROM main"
//val statement = db.compileStatement(sql)
//val result = statement.simpleQueryForLong()
//Convert barcode output to string
var barcodevalue = this.value.toString()
// hide settings
holder.itemView.textSettingsTitle.visibility=View.GONE
holder.itemView.textboxName.visibility=View.GONE
}

Upload attachment in corda

I have tried to upload a attachment in corda.
I have checked https://github.com/corda/corda/tree/release-M14. It is very complex and don't have a UI. When I tried to use some part of code it is showing full errors.
I have tried https://github.com/corda/blacklist . But here hash is finding in HTML page. Can I get a simple example to upload a document using UI and hash finding in kt file?
The blacklist sample here also has an example of uploading an attachment via RPC in Kotlin:
package net.corda.examples.attachments.client
import net.corda.client.rpc.CordaRPCClient
import net.corda.core.crypto.SecureHash
import net.corda.core.messaging.CordaRPCOps
import net.corda.core.utilities.NetworkHostAndPort.Companion.parse
import net.corda.core.utilities.loggerFor
import net.corda.examples.attachments.ATTACHMENT_EXPECTED_CONTENTS
import net.corda.examples.attachments.ATTACHMENT_FILE_NAME
import net.corda.examples.attachments.BLACKLIST_JAR_PATH
import org.slf4j.Logger
import java.io.File
import java.util.jar.JarInputStream
/**
* Uploads the jar of blacklisted counterparties with whom agreements cannot be struck to the node.
*/
fun main(args: Array<String>) {
UploadBlacklistClient().main(args)
}
private class UploadBlacklistClient {
companion object {
val logger: Logger = loggerFor<UploadBlacklistClient>()
}
fun main(args: Array<String>) {
require(args.isNotEmpty()) { "Usage: uploadBlacklist <node address>" }
args.forEach { arg ->
val nodeAddress = parse(arg)
val rpcConnection = CordaRPCClient(nodeAddress).start("user1", "test")
val proxy = rpcConnection.proxy
val attachmentHash = uploadAttachment(proxy, BLACKLIST_JAR_PATH)
logger.info("Blacklist uploaded to node at $nodeAddress")
val attachmentJar = downloadAttachment(proxy, attachmentHash)
logger.info("Blacklist downloaded from node at $nodeAddress")
checkAttachment(attachmentJar, ATTACHMENT_FILE_NAME, ATTACHMENT_EXPECTED_CONTENTS)
logger.info("Attachment contents checked on node at $nodeAddress")
rpcConnection.notifyServerAndClose()
}
}
}
/**
* Uploads the attachment at [attachmentPath] to the node.
*/
private fun uploadAttachment(proxy: CordaRPCOps, attachmentPath: String): SecureHash {
val attachmentUploadInputStream = File(attachmentPath).inputStream()
return proxy.uploadAttachment(attachmentUploadInputStream)
}
/**
* Downloads the attachment with hash [attachmentHash] from the node.
*/
private fun downloadAttachment(proxy: CordaRPCOps, attachmentHash: SecureHash): JarInputStream {
val attachmentDownloadInputStream = proxy.openAttachment(attachmentHash)
return JarInputStream(attachmentDownloadInputStream)
}
/**
* Checks the [expectedFileName] and [expectedContents] of the downloaded [attachmentJar].
*/
private fun checkAttachment(attachmentJar: JarInputStream, expectedFileName: String, expectedContents: List<String>) {
var name = attachmentJar.nextEntry.name
while (name != expectedFileName) {
name = attachmentJar.nextEntry.name
}
val contents = attachmentJar.bufferedReader().readLines()
if (contents != expectedContents) {
throw IllegalArgumentException("Downloaded JAR did not have the expected contents.")
}
}

CorDapp is working in CRaSH Shell but API is not recognizing CorDapp

I'm trying to expose an API for a CorDapp and the functions are not displaying. When looking at an example (https://github.com/roger3cev/obligation-cordapp), I receive the following page: https://imgur.com/a/ifOdrAd, however when I load my CorDapp, it says there are no installed Cordapps and /api on the localhost returns a 404. In the project, I feel the problem lies somewhere here: https://github.com/PronoyC/InsureFlight/tree/master/cordapp/src/main/kotlin/com/insureflight. I know this is very vague but I cannot find any errors that indicate a specific area. Any help would be appreciated.
InsureFlightApi.kt:
package com.insureflight
import net.corda.core.contracts.Amount
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.messaging.CordaRPCOps
import net.corda.core.utilities.OpaqueBytes
import net.corda.core.utilities.getOrThrow
import com.insureflight.flows.IssuePolicy
import com.insureflight.flows.PayoutPolicy
import net.corda.finance.contracts.asset.Cash
import net.corda.finance.contracts.getCashBalances
import net.corda.finance.flows.CashIssueFlow
import java.util.*
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.QueryParam
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.core.Response.Status.BAD_REQUEST
import javax.ws.rs.core.Response.Status.CREATED
#Path("insureflight")
class InsureFlightApi(val rpcOps: CordaRPCOps) {
private val myIdentity = rpcOps.nodeInfo().legalIdentities.first()
#GET
#Path("me")
#Produces(MediaType.APPLICATION_JSON)
fun me() = mapOf("me" to myIdentity)
#GET
#Path("peers")
#Produces(MediaType.APPLICATION_JSON)
fun peers() = mapOf("peers" to rpcOps.networkMapSnapshot()
.filter { nodeInfo -> nodeInfo.legalIdentities.first() != myIdentity }
.map { it.legalIdentities.first().name.organisation })
#GET
#Path("policies")
#Produces(MediaType.APPLICATION_JSON)
fun policies() = rpcOps.vaultQuery(Policy::class.java).states
#GET
#Path("cash")
#Produces(MediaType.APPLICATION_JSON)
fun cash() = rpcOps.vaultQuery(Cash.State::class.java).states
#GET
#Path("cash-balances")
#Produces(MediaType.APPLICATION_JSON)
fun getCashBalances() = rpcOps.getCashBalances()
#GET
#Path("self-issue-cash")
fun selfIssueCash(#QueryParam(value = "amount") amount: Int,
#QueryParam(value = "currency") currency: String): Response {
// 1. Prepare issue request.
val issueAmount = Amount(amount.toLong(), Currency.getInstance(currency))
val notary = rpcOps.notaryIdentities().firstOrNull() ?: throw IllegalStateException("Could not find a notary.")
val issueRef = OpaqueBytes.of(0)
val issueRequest = CashIssueFlow.IssueRequest(issueAmount, issueRef, notary)
// 2. Start flow and wait for response.
val (status, message) = try {
val flowHandle = rpcOps.startFlowDynamic(CashIssueFlow::class.java, issueRequest)
val result = flowHandle.use { it.returnValue.getOrThrow() }
CREATED to result.stx.tx.outputs.single().data
} catch (e: Exception) {
BAD_REQUEST to e.message
}
// 3. Return the response.
return Response.status(status).entity(message).build()
}
#GET
#Path("issue-policy")
fun issuePolicy(#QueryParam(value = "premium") premium: Int,
#QueryParam(value = "currency") currency: String,
#QueryParam(value = "client") client: String,
#QueryParam(value = "underwriter") underwriter: String,
#QueryParam(value = "flight") flight: String,
#QueryParam(value = "fStatus") fStatus: String): Response {
// 1. Create a premium object.
val issuePremium = Amount(premium.toLong() * 100, Currency.getInstance(currency))
// 2. Start the IssuePolicy flow. We block and wait for the flow to return.
val (status, message) = try {
val flowHandle = rpcOps.startFlowDynamic(
IssuePolicy.Initiator::class.java,
issuePremium,
client,
underwriter,
flight,
fStatus,
true
)
val result = flowHandle.use { it.returnValue.getOrThrow() }
CREATED to "Transaction id ${result.id} committed to ledger.\n${result.tx.outputs.single().data}"
} catch (e: Exception) {
BAD_REQUEST to e.message
}
// 3. Return the result.
return Response.status(status).entity(message).build()
}
#GET
#Path("payout-policy")
fun settlePolicy(#QueryParam(value = "id") id: String,
#QueryParam(value = "delayedMinutes") delayedMinutes: Int,
#QueryParam(value = "fStatus") fStatus: String): Response {
// 1. Get party objects for the counterparty.
val linearId = UniqueIdentifier.fromString(id)
// 2. Start the SettlePolicy flow. We block and wait for the flow to return.
val (status, message) = try {
val flowHandle = rpcOps.startFlowDynamic(
PayoutPolicy.Initiator::class.java,
linearId,
delayedMinutes,
fStatus,
true
)
flowHandle.use { flowHandle.returnValue.getOrThrow() }
CREATED to "Policy $linearId has been settled."
} catch (e: Exception) {
BAD_REQUEST to e.message
}
// 3. Return the result.
return Response.status(status).entity(message).build()
}
}
InsureFlightPlugin.kt (ObligationPlugin.kt is very similar to this):
package com.insureflight
import net.corda.core.messaging.CordaRPCOps
import net.corda.webserver.services.WebServerPluginRegistry
import java.util.function.Function
class InsureFlightPlugin : WebServerPluginRegistry {
override val webApis: List<Function<CordaRPCOps, out Any>> = listOf(Function(::InsureFlightApi))
override val staticServeDirs: Map<String, String> = mapOf(
"policy" to javaClass.classLoader.getResource("policyWeb").toExternalForm()
)
}
Kid101 is correct. You've to register the InsureFlightPlugin, like done here: obligation-cordapp/kotlin-source/src/main/resources/META-INF/services/net.corda.webserver.services.WebServerPluginRegistry

Resources