Categories
discuss

Basic usage of @react-native-firebase/admob gives: “TypeError: (0, _admob.default) is not a function”. Is it deprecated? or Why doesnt work?

Is @react-native-firebase/admob deprecated? or just.. Why it doesn’t work?

I am using @react-native-firebase/admob (https://rnfb-docs.netlify.app/admob/usage). Everything works fine before to use “admob()”. When I add admob() to the code appears this error:

“TypeError: (0, _admob.default) is not a function”

Do someone know why?

My code below (basic usage):

import React from 'react';
import { Text, View} from 'react-native';
import admob, { MaxAdContentRating } from '@react-native-firebase/admob';
import { InterstitialAd, RewardedAd, BannerAd, TestIds } from '@react-native- 
firebase/admob';
import { BannerAdSize} from '@react-native-firebase/admob';



class App extends React.Component{

componentDidMount(){

// this was taked of official page: https://rnfb-docs.netlify.app/admob/usage#installation
admob()
  .setRequestConfiguration({
    // Update all future requests suitable for parental guidance
    maxAdContentRating: MaxAdContentRating.PG,

    // Indicates that you want your content treated as child-directed for purposes of COPPA.
    tagForChildDirectedTreatment: true,

    // Indicates that you want the ad request to be handled in a
    // manner suitable for users under the age of consent.
    tagForUnderAgeOfConsent: true,
  })
  .then(() => {
    // Request config successfully set!
  });
 }
render(){
return(
  <View style={{
    alignItems:"center", 
    justifyContent:"center",
    height:"100%"}}>
    <Text style={{color:"black"}}>
      Hola
    </Text>
    <BannerAd 
      unitId={TestIds.BANNER} 
      size={BannerAdSize.FULL_BANNER} />
  </View>
  )
 }
}
 export default App;


   

Answer

I could solve it.

SOLVED

Just check in the file “package.json” that packages of firebase has the same version, example:

dependencies{
   "@react-native-firebase/admob": "^11.5.0",
   "@react-native-firebase/app": "^11.5.0"
}

TIP

Works to similars errors.

Categories
discuss

Filter array of objects through checkboxes

This is a React.js filter problem and I’m stuck here. The problem has static data of movies as an array of objects and we have to filter that data according to the checked state of different checkboxes.

Static Data:

export const data = [
    {
        id: 1,
        title: 'Batman',
        rating: 1,
        genre: 'Action'
    },
    {
        id: 2,
        title: 'Superman',
        rating: 5,
        genre: 'Comedy'
    },
    {
        id: 3,
        title: 'Spiderman',
        rating: 3,
        genre: 'Thriller'
    },
    {
        id: 4,
        title: 'BananaMan',
        rating: 2,
        genre: 'Action'
    },
    {
        id: 5,
        title: 'OrangeMan',
        rating: 4,
        genre: 'Drama'
    }
];

The abstract UI has the following picture that represents 2 types of filters.

  • Rating
  • Genre

Screenshot:

Filters screenshot

Both Filters are rendered on the UI as checkboxes. So, I’ve created a component called Checkboxes which will take a prop named list and it is an array of objects.

This list represents unique ids of checkboxes which will help us to track the checked or unchecked state of the checkbox. The different checkboxes id will save inside the state which is an array.

const [checkedArray, setCheckedArray] = useState([]);

Finally, I’m rendering this Checkboxes component twice inside the parent component called App.js. One for rating and the other for genre.

List:

export const listCheckboxesRating = [
    {
        id: 0,
        name: 'rating',
        label: 'Any Rating'
    },
    {
        id: 1,
        name: 'rating1',
        label: 'Rating 1'
    },
    {
        id: 2,
        name: 'rating2',
        label: 'Rating 2'
    },
    {
        id: 3,
        name: 'rating3',
        label: 'Rating 3'
    },
    {
        id: 4,
        name: 'rating4',
        label: 'Rating 4'
    },
    {
        id: 5,
        name: 'rating5',
        label: 'Rating 5'
    }
];

export const listCheckboxesGenre = [
    {
        id: 0,
        name: 'genre',
        label: 'Any Genre'
    },
    {
        id: 1,
        name: 'action',
        label: 'Action'
    },
    {
        id: 2,
        name: 'comedy',
        label: 'Comedy'
    },
    {
        id: 3,
        name: 'drama',
        label: 'Drama'
    },
    {
        id: 4,
        name: 'thriller',
        label: 'Thriller'
    }
];

Checkboxes component:

import {useState} from 'react';
import {handleToggle} from '../../utils';

const Checkboxes = ({list, handleFilters}) => {
    const [checkedArray, setCheckedArray] = useState([]);

    const onChangeHandler = (checkboxId) => {
        const newState = handleToggle(checkboxId, checkedArray);
        setCheckedArray(newState);
        // Update this checked information into Parent Component
        handleFilters(newState);
    };

    return list.map((item, index) => {
        return (
            <div key={index}>
                <input
                    type="checkbox"
                    id={item.name}
                    checked={checkedArray.indexOf(item.id) !== -1}
                    onChange={() => onChangeHandler(item.id)}
                />
                <label htmlFor={item.name}>{item.label}</label>
            </div>
        );
    });
};

export default Checkboxes;

I’m passing the whole state of these checkboxes through a function named handleFilters to parent component App.js. You can see this line of code.

handleFilters(newState);

The App.js component is saving states of these checkboxes with something like this:

 const [selected, setSelected] = useState({
        rating: [],
        genre: []
    });

App.js component:

import {useState} from 'react';
import Checkboxes from './Checkboxes';
import {data, listCheckboxesRating, listCheckboxesGenre} from '../data';

const App = () => {
    const [movies, setMovies] = useState(data);
    const [selected, setSelected] = useState({
        rating: [],
        genre: []
    });

    /**
     * This function will perform the filtration process based on the key value.
     *
     * @param {number[]} checkboxState - It will take the final state of checkboxes
     * @param {string} key - It will help us to determine the type of filtration
     */
    const handleFilters = (checkboxState, key) => {
        const newFilters = {...selected};
        newFilters[key] = checkboxState;
        // Filtration process
        for (let key in newFilters) {
            if (
                newFilters.hasOwnProperty(key) &&
                Array.isArray(newFilters[key]) &&
                newFilters[key].length > 0
            ) {
                if (key === 'rating') {
                } else if (key === 'genre') {
                }
            }
        }

        // Save the filtered movies and update the state.
        //  setMovies();
        setSelected(newFilters);
    };

    return (
        <div>
            {movies.map((movie) => (
                <div key={movie.id}>
                    <div>Name: {movie.title}</div>
                    <div>Genre :{movie.genre}</div>
                    <div>Rating: {movie.rating}</div>
                    <hr />
                </div>
            ))}

            <div className="row">
                <div className="col">
                    <h1>Filter by Rating</h1>
                    <Checkboxes
                        list={listCheckboxesRating}
                        handleFilters={(checkboxState) =>
                            handleFilters(checkboxState, 'rating')
                        }
                    />
                </div>

                <div className="col">
                    <h1>Filter by Genre</h1>
                    <Checkboxes
                        list={listCheckboxesGenre}
                        handleFilters={(checkboxState) =>
                            handleFilters(checkboxState, 'genre')
                        }
                    />
                </div>
            </div>
        </div>
    );
};

export default App;

The checkboxes checked or unchecked state of both filters are working fine and correctly updated with ids inside the parent selected state with something like this.

 const [selected, setSelected] = useState({
            rating: [1,2,3],
            genre: [2,4]
        });

But here is the confusing part where I’m stuck. How to map these checkboxes ids and filter the data according to these ids?

I’ve defined a function in the App.js component handleFilters(checkboxState, key) in which I wanted to iterate the selected state to perform the filtration process but my mind is not making logic and I need help.

WORKING DEMO:

Edit react-filter

repository link.

Answer

I did some refactoring.

  1. Made data more generic.
    export const listCheckboxesRating = {
      key: 'rating',
      data: [
        {
          id: 1,
          name: 'rating1',
          label: 'Rating 1',
          value: 1
        },
        ...
    }
  1. Refactor Checkbox component and just pass data.
    <Checkboxes
      list={listCheckboxesGenre}
      handleFilters={handleFilters}
    />
  1. Made filtration process work with value and key.
    // Filtration process
    let filteredMovies = data.filter((movie) => {
      for (let key in newFilters) {
        if (
          newFilters.hasOwnProperty(key) &&
          Array.isArray(newFilters[key]) &&
          newFilters[key].length > 0
        ) {
          if (
            newFilters[key].findIndex((value) => movie[key] === value) === -1
          ) {
            return false;
          }
        }
      }
      return true;
    });

Working DEMO: https://codesandbox.io/s/react-filter-forked-gs2b2?file=/src/components/App.js

Categories
discuss

Getting Execution failed for task ‘:app:kaptDebugKotlin’. when trying to implement Room component

I’m working on a small project on Android studio. I am currently using canary version of android studio for m1 mac. When I try to implement room, I get following error:

Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:207)
    at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:263)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:205)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:186)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:114)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:409)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:399)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:157)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:242)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:150)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:94)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:41)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:356)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
    at org.gradle.workers.internal.DefaultWorkerExecutor$WorkItemExecution.waitForCompletion(DefaultWorkerExecutor.java:336)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:142)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.access$000(DefaultAsyncWorkTracker.java:34)
    at org.gradle.internal.work.DefaultAsyncWorkTracker$1.run(DefaultAsyncWorkTracker.java:106)
    at org.gradle.internal.Factories$1.create(Factories.java:26)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withoutLocks(DefaultWorkerLeaseService.java:251)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withoutProjectLock(DefaultWorkerLeaseService.java:162)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withoutProjectLock(DefaultWorkerLeaseService.java:156)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withoutProjectLock(StopShieldingWorkerLeaseService.java:95)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:102)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForAll(DefaultAsyncWorkTracker.java:80)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForCompletion(DefaultAsyncWorkTracker.java:68)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$3.run(ExecuteActionsTaskExecuter.java:577)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:395)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:387)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:157)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:242)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:150)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:84)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:554)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:537)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$300(ExecuteActionsTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.executeWithPreviousOutputFiles(ExecuteActionsTaskExecuter.java:278)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:267)
    at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$0(ExecuteStep.java:32)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:32)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:67)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:36)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:49)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:34)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:43)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
    at org.gradle.internal.execution.steps.CatchExceptionStep.execute(CatchExceptionStep.java:34)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:44)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:54)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:38)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:49)
    at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:159)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:72)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:43)
    at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:44)
    at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:33)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:92)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:85)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:55)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:39)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:76)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:94)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:49)
    at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:79)
    at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:53)
    at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:74)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.lambda$execute$2(SkipEmptyWorkStep.java:78)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:78)
    at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:34)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:39)
    at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:40)
    at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:28)
    at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:194)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:186)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:114)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:409)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:399)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:157)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:242)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:150)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:94)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:41)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:356)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
Caused by: java.lang.reflect.InvocationTargetException
    at org.jetbrains.kotlin.gradle.internal.KaptExecution.run(KaptWithoutKotlincTask.kt:232)
    at org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction.execute(KaptWithoutKotlincTask.kt:198)
    at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:63)
    at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:67)
    at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.create(NoIsolationWorkerFactory.java:63)
    at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:97)
    at org.gradle.workers.internal.NoIsolationWorkerFactory$1.lambda$execute$0(NoIsolationWorkerFactory.java:63)
    at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
    at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:409)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:399)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:157)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:242)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:150)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:94)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
    at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:60)
    at org.gradle.workers.internal.DefaultWorkerExecutor.lambda$submitWork$2(DefaultWorkerExecutor.java:200)
    at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
    at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
    at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
    ... 3 more
Caused by: org.jetbrains.kotlin.kapt3.base.util.KaptBaseError: Error while annotation processing
    at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:121)
    at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:31)
    at org.jetbrains.kotlin.kapt3.base.Kapt.kapt(Kapt.kt:45)
    ... 25 more

I tried almost everything that I found. My gradle files: project – build.gradle:

buildscript {
    ext {
        appcompat_version = "1.3.0"
        constraintlayout_version = "2.0.4"
        core_ktx_version = "1.5.0"
        kotlin_version = "1.5.10"
        material_version = "1.3.0"
        nav_version = "2.3.5"
        room_version = "2.3.0"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"

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

allprojects {
    repositories {
        google()
        jcenter()
    }
        configurations.all {
            resolutionStrategy {
                force 'org.xerial:sqlite-jdbc:3.34.0'
            }

And my app level gradle:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt'
    id 'androidx.navigation.safeargs.kotlin'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.moviedb"
        minSdkVersion 21
        targetSdkVersion 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'
    }

    buildFeatures {
        dataBinding true
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation "androidx.core:core-ktx:$core_ktx_version"
    implementation "androidx.appcompat:appcompat:$appcompat_version"
    implementation "com.google.android.material:material:$material_version"
    implementation "androidx.constraintlayout:constraintlayout:$constraintlayout_version"
    implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
    implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.2.0'
    implementation 'com.github.bumptech.glide:glide:4.12.0'

    //Room
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation "androidx.room:room-ktx:$room_version"

    // Moshi
    implementation 'com.squareup.moshi:moshi-kotlin:1.11.0'

    // Retrofit with Moshi Converter
    implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'

    // Coil
    implementation "io.coil-kt:coil:1.1.1"
}

Does anyone have idea how to solve?

Answer

In case if you have not found the answer here you go.

The problem is explained here and has a workaround too.

https://issuetracker.google.com/issues/174695268#comment9

Categories
discuss

Jetpack Compose Scaffold + Modal Bottom Sheet

I’m trying to design a layout using Compose that consists of:

  1. TopAppBar
  2. Body (content)
  3. BottomAppBar
  4. A Bottom Sheet that represents a menu when clicked (Modal Bottom Sheet)

——-TopAppBar——-

——MainContent——

——BottomAppBar—–

—-ModalBottomSheet—

Compose offers 3 components:

  1. Scaffold
  2. BottomSheetScaffold
  3. ModalBottomSheetLayout

Scaffold has no bottom sheet property

BottomSheetScaffold has no BottomAppBar property

ModalBottomSheetLayout has only content and sheetContent

Which of these components should I combine and in what **structure** to achieve what I want?

Scaffold(
  topBar = { TopBar() },
  content = { innerPadding -> Body(innerPadding) },
  bottomAppbar = { BottomAppBar() }
)
ModalBottomSheetLayout(
  sheetState = rememberModalBottomSheetState(
    initialValue = ModalBottomSheetValue.Hidden
  ),
  sheetContent = { SheetContent() },
)
BottomSheetScaffold(
  scaffoldState = ...,
  sheetContent = { SheetContent() },
  content = { ScreenContent() },
)

Answer

You can use something like:

val bottomState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
ModalBottomSheetLayout(
    sheetState = bottomState,
    sheetContent = {
        //. sheetContent
    }
) {
    Scaffold(
        scaffoldState = scaffoldState,
        topBar = {
            TopAppBar(
                title = {
                    Text(text = "TopAppBar")
                }
            )
        },
        bottomBar = {
            BottomAppBar(modifier = Modifier) {
                IconButton(
                    onClick = {
                        coroutineScope.launch { bottomState.show() }  
                    }
                ) {
                    Icon(Icons.Filled.Menu, contentDescription = "Localized description")
                }
            }
        },

        content = { innerPadding ->
            //...main content
        }
    )
}

enter image description here

Categories
discuss

Converting TableLayout to RecyclerView

I’m trying to convert my TableLayout to a RecyclerView. The TableLayout is fine so far as it goes, but some of the tables have lots of rows, and are really slow to inflate, and I think that a RecyclerView would be the more efficient model to use (and would allow easy access to searching/filtering functionality).

The issue I’m having is that my TableLayout is defined as a set of custom views or compound controls, with a few standard views thrown in, like so:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    style="@style/MySection"
    android:id="@+id/section_cape" >

    <TableLayout style="@style/MyTable"
        android:id="@+id/table_cape" >

        <com.example.myapp.CompoundSwitch
            android:id="@+id/cape"
            custom:switch_label_tag="label_show"
            custom:switch_label_text="@string/label_show"
            custom:switch_indented="false"
            android:visibility="visible" />

        <TextView
            style="@style/MyTextView"
            android:id="@+id/info_capeNotAvailable"
            android:text="@string/info_notAvailable" />

        <com.example.myapp.CompoundSpinner
            android:id="@+id/capeProvider"
            custom:spinner_label_tag="label_variableProvider"
            custom:spinner_label_text="@string/label_provider"
            custom:spinner_indented="false"
            android:visibility="visible" />

        <com.example.myapp.CompoundSlider
            android:id="@+id/capeTransition"
            custom:slider_label_tag="label_providerTransition"
            custom:slider_label_text="@string/label_transition"
            custom:slider_indented="true"
            custom:slider_range="false"
            android:visibility="gone" />

        ... etc ...

Each of the custom views is defined as a TableRow.

I’m struggling to understand what to inflate in the onCreateViewHolder() method of my Adapter. Of course, each custom view does have a layout, but for some of these custom views, there are several layouts and a different layout is used depending on what custom attributes are defined in the xml.

So how do I map my rows of custom views (each with its own set of attributes) into the RecyclerView structure?

My current thinking is that I would have to move each row (custom view) statement into its own separate layout xml file, and then inflate the appropriate one of these in the onCreateViewHolder() method (based on viewType) but I’m not sure that this is the correct approach… and there would be a lot of very small layout files… seems unnecessarily unwieldy.

Answer

My current thinking is that I would have to move each row (custom view) statement into its own separate layout xml file, and then inflate the appropriate one of these in the onCreateViewHolder() method (based on viewType) but I’m not sure that this is the correct approach… and there would be a lot of very small layout files… seems unnecessarily unwieldy.

You’re right, but with some small correction. It seems like you want to set different custom attributes for many custom Views. So, you don’t need to create a lot of small layout files. Instead, you can move these attributes into the code.

  1. At first we define class RowDescriptor which will hold layoutId, factory of ViewHolder instances and the values of your custom attributes.
class RowDescriptor {
  int layoutId;
  RowViewHolder.Factory factory;
  Map<String, Object> values = new HashMap<>();

  public int getLayoutId() { return layoutId; }

  public RowViewHolder.Factory getFactory() { return factory; }

  RowDescriptor(int layoutId, RowViewHolder.Factory factory) {
    this.layoutId = layoutId;
    this.factory = factory;
  }

  public <T> T getValue(String key) {
    return (T) values.get(key);
  }

  public <T> RowDescriptor putValue(String key, T value) {
    values.put(key, value);
    return this;
  }
}
class RowViewHolder extends RecyclerView.ViewHolder {
  RowViewHolder(View itemView) {
    super(itemView);
  }

  void onBind(RowDescriptor row) {
    // for inheritors
  }

  interface Factory {
    RowViewHolder newInstance(View itemView);
  }
}
  1. Then do the trick inside the Adapter implementation. Method onCreateViewHolder() receive only int viewType, and we must convert it to layoutId and create corresponding ViewHolder. So, take a look at the method getItemViewType(), all the magic happens there.
class RowsAdapter extends RecyclerView.Adapter<RowViewHolder> {
  List<? extends RowDescriptor> rows;
  SparseIntArray layoutIdToViewType = new SparseIntArray();
  SparseIntArray viewTypeToLayoutId = new SparseIntArray();
  SparseArray<RowViewHolder.Factory> viewTypeToFactory = new SparseArray<>();

  void setData(List<RowDescriptor> rows) {
    this.rows = rows;
    notifyDataSetChanged();
  }

  int getItemCount() {
    return rows != null ? rows.size() : 0;
  }

  int getItemViewType(int position) {
    RowDescriptor row = rows.get(position);

    int viewType = layoutIdToViewType.get(row.getLayoutId());
    if (viewType == 0) {
      viewType = layoutIdToViewType.size() + 1;

      layoutIdToViewType.put(row.getLayoutId(), viewType);
      viewTypeToLayoutId.put(viewType, row.getLayoutId());
      viewTypeToFactory.put(viewType, row.getFactory());
    }

    return viewType;
  }

  RowViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
      .inflate(viewTypeToLayoutId.get(viewType), parent, false);

    return viewTypeToFactory.get(viewType).newInstance(view);
  }

  void onBindViewHolder(RowViewHolder holder, int position) {
    holder.onBind(rows.get(position));
  }
}
  1. Then create needed layouts and corresponding ViewHolder classes. IMPORTANT: same ViewHolder class may be used with different layouts, but same layout can not be used with different ViewHolder classes!

res/layout/row1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal">

  <TextView
    android:id="@+id/some_value"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

  <TextView
    android:id="@+id/label"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1" />
</LinearLayout>
class FirstRowViewHolder extends RowViewHolder {
  TextView someValueView;
  TextView labelView;

  FirstRowViewHolder(View itemView) {
    super(itemView);
    someValueView = itemView.findViewById(R.id.some_value);
    labelView = itemView.findViewById(R.id.label);
  }

  void onBind(RowDescriptor row) {
    Integer someValue = row.getValue("some_value");
    someValueView.setText(String.valueOf(someValue));

    String label = row.getValue("label");
    labelView.setText(label);
  }
}

res/layout/row2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal">

  <TextView
    android:id="@+id/another_value"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

  <TextView
    android:id="@+id/description"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1" />
</LinearLayout>
class SecondRowViewHolder extends RowViewHolder {
  TextView anotherValueView;
  TextView descriptionView;

  SecondRowViewHolder(View itemView) {
    super(itemView);
    anotherValueView = itemView.findViewById(R.id.another_value);
    descriptionView = itemView.findViewById(R.id.description);
  }

  void onBind(RowDescriptor row) {
    Integer anotherValue = row.getValue("another_value");
    anotherValueView.setText(String.valueOf(anotherValue));

    String description = row.getValue("description");
    descriptionView.setText(description);
  }
}
  1. Eventually, link everything together.
class MainActivity extends AppCompatActivity {
  void onCreate(Bundle state) {
    super.onCreate(state);

    List<RowDescriptor> rows = new ArrayList<>();

    rows.add(new RowDescriptor(R.layout.row1, FirstRowViewHolder::new)
        .putValue("some_value", 42)
        .putValue("label", "hello"));

    rows.add(new RowDescriptor(R.layout.row2, SecondRowViewHolder::new)
        .putValue("another_value", 24)
        .putValue("description", "world"));

    RowsAdapter adapter = new RowsAdapter();
    adapter.setData(rows);

    RecyclerView recyclerView = new RecyclerView(this);
    recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    recyclerView.setAdapter(adapter);

    setContentView(recyclerView);
  }
}

You can improve this solution by avoiding usage of Map for attribute values. Instead, you can create one more class hierarchy for entity, which will hold attribute values for each of your custom rows.

Compilable and workable project is here.

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