Categories
discuss

Firebase Modular SDK V9.0.0+ TypeError: Cannot read property ‘apps’ of undefined firebase

I got this error when trying to run my next.js app. I try lots of ways but I can’t solve this. I am using firebase 9.0.1

Server Error
TypeError: Cannot read property 'apps' of undefined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
.nextserverpages_app.js (14:13) @ Object../firebase.js

  12 | };
  13 |
> 14 | const app = !firebase.apps.length
     |             ^
  15 |   ? firebase.initializeApp(firebaseConfig)
  16 |   : firebase.app();

Here is my firebase.js

import firebase from "firebase/app";

// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

const app = !firebase.apps.length
  ? firebase.initializeApp(firebaseConfig)
  : firebase.app();

const db = app.firestore();
const auth = app.auth();
const provider = new firebase.auth.GoogleAuthProvider();

export { db, auth, provider };

Answer

Since you are using the new Modular SDK v9.0.1 which does not use firebase. namespace, you should use getApps() instead of firebase.apps.

import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"

const firebaseConfig = {...}

if (!getApps().length) {
  //....
}

const app = initializeApp(firebaseConfig)

const db = getFirestore(app)
const auth = getAuth(app)

export {db, auth}

However, you don’t need to check if Firebase is already initialized in this new SDK. You can learn more about the new syntax in the documentation.

Also check: Getting started with Firebase for web

Categories
discuss

Compose: wrap text in Row layout, instead of pushing siblings out

I’m dipping my toes into Jetpack Compose, but I’m stumped by the behaviour of Row. I have a text next to an icon button, and I want the icon button to be anchored to the side with a minimum width of 48dp, and have text wrap around it. Like this:

Layout goal

But the text does not wrap, it eats up all the space in the Row:

Layout previews

@Composable
fun SampleLayout(text: String) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                    ) {
                        Text(text)
                        IconButton(
                            onClick = {  },
                        ) {
                            Icon(
                                imageVector = androidx.compose.material.icons.Icons.Default.StarBorder,
                                null
                            )
                        }
                    }
}

@Preview(showBackground = true, backgroundColor = 0x006EAEA0, fontScale = 1.5F)
@Composable
fun SamplePreview1() {
    Box(Modifier.padding(16.dp)) {
        SampleLayout("helooooo")
    }
}

@Preview(showBackground = true, backgroundColor = 0x006EAEA0, fontScale = 1.5F)
@Composable
fun SamplePreview2() {
    Box(Modifier.padding(16.dp)) {
        SampleLayout("helooooooooooooooooooooooooooo")
    }
}
@Preview(showBackground = true, backgroundColor = 0x006EAEA0, fontScale = 1.5F)
@Composable
fun SamplePreview3() {
    Box(Modifier.padding(16.dp)) {
        SampleLayout("heloooooooooooooooooooooooooooooooooooooooo")
    }
}

I’ve tried setting the minimum width of the icon 48dp, but the text then still fills until the end of the row.

How can I make sure the the Text width does not go further than the icon button?

Answer

By default Text has a higher layout priority than Icon in order to fill the necessary space. You can change this with the weight modifier.

After using this modifier, the size of Icon will be calculated before Text:

The parent will divide the vertical space remaining after measuring unweighted child elements

Also weight has a fill parameter, which is set to true by default. This is equivalent to fillMaxWidth (when weight is used inside a Row), so you can skip the fillMaxWidth modifier in your parent. When you don’t need this behaviour, pass false to this parameter.

Row(
    horizontalArrangement = Arrangement.SpaceBetween,
) {
    Text(text, modifier = Modifier.weight(1f))
    IconButton(
        onClick = { }
    ) {
        Icon(
            imageVector = Icons.Default.StarBorder,
            null
        )
    }
}
Categories
discuss

Ad failed to load with error code 0(internal Error) – Huawei Ads Implementation

I m getting the above error continuously in demo Application. I have HMS core Version 5.0.0.329(Initial Version). My internet connection is stable. I have created test application on app gallery that has been approved but still same error. No luck yet.

*Note: This Error only occurs on Huawei Device Y6p – Model- MED-LX9 -Android Version -10. Ads Showing on Samsung S7 – Android Version – 7.0

Following is the code for my test application. I m using Android studio Arctic Fox 2020.3.1

Module.gradle:

plugins {
id 'com.android.application'
id 'kotlin-android'
id 'com.huawei.agconnect'
}

android {
compileSdk 30

defaultConfig {
    applicationId "com.example.huaweitestads"
    minSdk 21
    targetSdk 30
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
    jvmTarget = '1.8'
}
}

dependencies {

implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

//Huawei Dependency
implementation 'com.huawei.agconnect:agconnect-core:1.5.2.300'
implementation 'com.huawei.hms:ads-lite:13.4.45.308'
//implementation 'com.huawei.hms:ads:3.4.45.308'
implementation 'com.huawei.hms:ads-identifier:3.4.34.301'
}

Project.gradle

    // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.21"
classpath 'com.huawei.agconnect:agcp:1.6.0.300'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

setting.gradle

dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
jcenter() // Warning: this repository is going to shut down soon
maven {url 'https://developer.huawei.com/repo/'}
}
}
rootProject.name = "HuaweiTestAds"
include ':app'

MainActivity:

class MainActivity : AppCompatActivity() {
private val adListener: AdListener = object : AdListener(){
override fun onAdClosed() {
showToast("Ad closed")
}

    override fun onAdFailed(p0: Int) {
        showToast(String.format(Locale.ROOT, "Ad failed to load with error code %d.", p0))
    }

    override fun onAdLeave() {
        showToast("Ad Leave")
    }

    override fun onAdOpened() {
        showToast(String.format("Ad opened "))
    }

    override fun onAdLoaded() {
        showToast("Ad loaded.")
    }

    override fun onAdClicked() {
        showToast("Ad clicked")
    }

    override fun onAdImpression() {
        showToast("Ad Impression")
    }
}
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //initialize the Huawei Ads
    HwAds.init(this)

    val bannerView: BannerView? = findViewById(R.id.hw_banner_view)
    bannerView!!.adListener = adListener
    bannerView.setBannerRefresh(30)
    val adParam = AdParam.Builder().build()
    bannerView.loadAd(adParam)
}
private fun showToast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}

activity.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:hwads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cl_root_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="hello "
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.huawei.hms.ads.banner.BannerView
    android:id="@+id/hw_banner_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/textView"
    hwads:adId="testw6vs28auh3"
    hwads:bannerSize="BANNER_SIZE_320_50" />
</androidx.constraintlayout.widget.ConstraintLayout>

logCat Exception: 2021-08-27 15:11:48.642 20928-20928/? E/LoadedApk: Unable to instantiate appComponentFactory java.lang.ClassNotFoundException: Didn’t find class “androidx.core.app.CoreComponentFactory” on path: DexPathList[[zip file “/data/app/com.huawei.appmarket-KidEWN7eyzOMAnU7Zs1jjg==/base.apk”],nativeLibraryDirectories=[/data/app/com.huawei.appmarket-KidEWN7eyzOMAnU7Zs1jjg==/lib/arm, /data/app/com.huawei.appmarket-KidEWN7eyzOMAnU7Zs1jjg==/base.apk!/lib/armeabi-v7a, /system/lib, /hw_product/lib, /system/product/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:209) at java.lang.ClassLoader.loadClass(ClassLoader.java:379) at java.lang.ClassLoader.loadClass(ClassLoader.java:312) at android.app.LoadedApk.createAppFactory(LoadedApk.java:270) at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:922) at android.app.LoadedApk.getClassLoader(LoadedApk.java:1044) at android.app.LoadedApk.getResources(LoadedApk.java:1293) at android.app.ContextImpl.createAppContext(ContextImpl.java:2610) at android.app.ContextImpl.createAppContext(ContextImpl.java:2598) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:7222) at android.app.ActivityThread.access$2400(ActivityThread.java:308) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2295) at android.os.Handler.dispatchMessage(Handler.java:110) at android.os.Looper.loop(Looper.java:219) at android.app.ActivityThread.main(ActivityThread.java:8349) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)

Exception 2:

2021-08-27 15:11:31.275 20725-20779/? E/ServiceRegistrarParser: get ServiceDiscovery exception.ComponentInfo{com.huawei.hms.agclink/com.huawei.agconnect.core.ServiceDiscovery} 2021-08-27 15:11:31.298 17647-18622/? E/fwkit_kitProviderDispatcher: [E/fwkit/fwkit_kitProviderDispatcher 17647:4417 StubContentProvider.java:153] NameNotFoundException android.content.pm.PackageManager$NameNotFoundException at android.app.ApplicationPackageManager.getPackageInfoAsUser(ApplicationPackageManager.java:201) at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:170) at com.huawei.hms.fwkit.kams.provideragent.a.a(KitProviderDispatcher.java:387) at com.huawei.hms.fwkit.kams.provideragent.a.a(KitProviderDispatcher.java:320) at com.huawei.hms.fwkit.kams.provideragent.StubContentProvider.getType(StubContentProvider.java:153) at android.content.ContentProvider$Transport.getType(ContentProvider.java:295) at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:140) at android.os.Binder.execTransactInternal(Binder.java:1028) at android.os.Binder.execTransact(Binder.java:1001)

Exception 3:

2021-08-27 15:12:07.512 4661-4736/? E/PushLog110102300: [SocketRead_15:10:54-308]read socket occurs Exception: com.huawei.android.pushagent.datatype.exception.PushException ra nra* Ei ee.ck(Unknown Source:101) ee.run(Unknown Source:40)

Any help would be appreciated.Thanks

Answer

Huawei Y6p has encountered the same problem before on this device. You can check there is a SIM card.

After the SIM is inserted, the country code of the SIM card will be read. Rules for obtaining the country code: country code of the place of shipment> country code of the sim card> country set by the mobile phone.

Categories
discuss

Thread-safety of NIO2 CompletionHandler

Is the following code thread-safe? If so, what guarantees the safe publication of the ByteBuffer instance to the thread executing the CompletionHandler?

AsynchronousSocketChannel channel = ...
ByteBuffer buf = ByteBuffer.allocate(1024);
channel.read(buf, null, new CompletionHandler<Integer, Void>() {

    //"completed" can be executed by a different thread than channel.read()
    public void completed(Integer result, Void attachment) {                
        buf.flip(); //Can buf be safely accessed here? If so, why?   
        //...          
    }

    public void failed(Throwable exc, Void attachment) {
       //...
    }
});

Answer

an authoritative reference that is valid for all JVMs and all platforms

The only such authoritative source I know of is javadocs (1, 2, 3).

Unfortunately, as you can see for yourself, they contain no explicit and clear guarantees of thread-safety.

It means the code is not thread-safe.


IMO the guarantees should be given in the javadoc for the method, the method’s class, or CompletionHandler — then we can be sure they are implemented for all JVMs and all platforms (and will stay implemented in the future).

But if you really want, you can “compile” a proof for thread-safety from multiple places in different javadocs:

  • AsynchronousSocketChannel.read(...):

    The handler parameter is a completion handler that is invoked when the read operation completes (or fails).

  • java.nio.channels:

    Asynchronous channels are bound to an asynchronous channel group for the purpose of resource sharing. A group has an associated ExecutorService to which tasks are submitted to handle I/O events and dispatch to completion handlers that consume the result of asynchronous operations performed on channels in the group.

  • ExecutorService:

    Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task

As a result, we get that every action of the I/O read to ByteBuffer happens-before the first action of CompletionHandler => this means the code is thread-safe.

IMO “compiled proofs” like the one above are too fragile, and personally I would assume that the code is not thread-safe.

Categories
discuss

How to change api level 29 to 30 in expo react native App

This Message was appear when i upload my app bundle to play store

Your app currently targets API level 29 and must target at least API level 30 to ensure it is built on the latest APIs optimized for security and performance. Change your app’s target API level to at least 30.

Answer

If you have a managed workflow expo app.
To make expo target new Api level 30, you need to upgrade your app to Expo SDK 41 or higher.
Do the following ;

  1. Upgrade your expo cli to 41 or higher – npm i -g expo-cli expo-cli@4.4.1
  2. Run expo upgrade on your project
  3. Create a new build of your app for Google Paystore – expo build:android

This will now target api 30

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..