Categories
discuss

Flutter read all files from asset folder

I have an assets folder in which I have a tab folder and then a list of folders and each folder contains some files

enter image description here

Now I want to read the names of all the folders that are in the tabs folder and all the files that are in each subfolder of the tabs folder, i.e. folders that are named as sound 1, sound 2, sound 3 …..

In simple words, I want to read names of all files and folders that are in my assets folder. Please Anyone help. Thanks,

Answer

Even if you specified only asset folders in pubspec.yaml, the flutter compiler lists all files from these folders in AssetManifest.json file. All we have to do is read this file:

final manifestJson = await DefaultAssetBundle.of(context).loadString('AssetManifest.json');
final images = json.decode(manifestJson).keys.where((String key) => key.startsWith('assets/images'));
Categories
discuss

When Fragment onActivityCreated called

Before Google architecture component and LiveData I have not paid attention to onActivityCreated() callback. I read about this here in SOF as well in documentation, and i still cannot understand the behavior.

From one of SOF answers:

As the name states, this is called after the Activity’s onCreate() has completed.

  • In which conditions onActivityCreated() called and when onActivityCreated() not called?

  • is it possible that onCreateView() called but onActivityCreated() not called?

It common practice to attach LiveData observers in onActivityCreated(), so i guess there are significant difference between onActivityCreated() and onCreateView()?

Although looking on the diagram from official Android docs seems like it onActivityCreated() is called always after onCreateView()(in terms of execution, not order) and there no diffrence?

Something confusing here.

enter image description here

UPDATE: onActivityCreated() deprecated.

Answer

EDIT: According to Ian Lake on Twitter (see https://twitter.com/ianhlake/status/1193964829519667202), the fact that FragmentActivity attempts to dispatch onActivityCreated in onStart is irrelevant, because no matter what happens, the FragmentManager dispatches it anyway when going from onCreate to onStart.

            case Fragment.CREATED:
                // We want to unconditionally run this anytime we do a moveToState that
                // moves the Fragment above INITIALIZING, including cases such as when
                // we move from CREATED => CREATED as part of the case fall through above.
                if (newState > Fragment.INITIALIZING) {
                    fragmentStateManager.ensureInflatedView();
                }
                if (newState > Fragment.CREATED) {
                    fragmentStateManager.createView(mContainer);
                    fragmentStateManager.activityCreated(); // <--
                    fragmentStateManager.restoreViewState();

So what I said below is actually wrong.

Apparently using onActivityCreated inside a Fragment is equivalent to using onViewCreated.

But this also means you shouldn’t rely on onActivityCreated to know if your Activity was actually created, because it is called more times than when the Activity is actually created.

Fragments are confusing.



ORIGINAL ANSWER:

Is it possible that onCreateView() called but onActivityCreated() not called?

UPDATE: No, it’s not possible.

ORIGINAL: Yes, in a FragmentPagerAdapter they use FragmentTransaction.detach / FragmentTransaction.attach, which causes the View to be destroyed, but the Fragment stays alive (stopped, but not destroyed).

In this case, .attach() runs onCreateView, but not onActivityCreated.

It’s common practice to attach LiveData observers in onActivityCreated(), so i guess there are significant difference between onActivityCreated() and onCreateView()?

UPDATE: it doesn’t matter, although onViewCreated is still clearer.

ORIGINAL: It’s actually a bad practice, and should be done in onViewCreated, providing getViewLifecycleOwner() as the lifecycle owner.

Although looking on the diagram from official Android docs seems like it onActivityCreated() is called always after onCreateView() and there no diffrence?

UPDATE: Despite that the FragmentActivity only tries to dispatch it once, all Fragments always go through onActivityCreated, because that’s just how the FragmentManager works.

ORIGINAL: It is not always called after onCreateView, in fact, it’s more-so called “before onStart, but only once”.

/**
 * Dispatch onStart() to all fragments.
 */
@Override
protected void onStart() {
    super.onStart();

    mStopped = false;

    if (!mCreated) {
        mCreated = true;
        mFragments.dispatchActivityCreated(); // <---
    }

    mFragments.noteStateNotSaved();
    mFragments.execPendingActions();

    // NOTE: HC onStart goes here.

    mFragments.dispatchStart();
}

UPDATE: but apparently this doesn’t really matter to the FragmentManager, because it goes CREATED -> ACTIVITY_CREATED -> STARTED either way.

Categories
discuss

VueJS decode base64 html string

So that I can implement a live preview for uploadable HTML files, I need help decoding the base64 string.

When I pass a file to the input element and read it with FileReader(), I get a base64 encoded string.

What do I have to do to convert it to HTML/TXT?

I already found some stuff about decoding pictures, which unfortunately didn’t help me.

handleFileUpload() {
          this.file = this.$refs.file.files[0];
          let reader = new FileReader();

          reader.addEventListener("load", function() {
            this.html = atob(reader.result);
          }.bind(this), false);

          reader.readAsDataURL(this.file);
        },

Output:

data:text/html;base64,PGh0bWwgeG1sbnM6dj0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp2bWwiDQp4bWxuczpvPSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOm9mZmljZTpvZmZpY2UiDQp4bWxuczp4PSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOm9mZmljZTpleGNlbCINCnhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy9UUi9SRUMtaHRtbDQwIj4NCg0KPGhlYWQ+DQo8bWV0YSBodHRwLWVxdWl2PUNvbnRlbnQtVHlwZSBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9d2luZG93cy0xMjUyIj4NCjxtZXRhIG5hbWU9UHJvZ0lkIGNvbnRlbnQ9RXhjZWwuU2hlZXQ+DQo8bWV0YSBuYW1lPUdlbmVyYXRvciBjb250ZW50PSJNaWNyb3NvZnQgRXhjZWwgMTUiPg0KPGxpbmsgaWQ9TWFpbi1GaWxlIHJlbD1NY......

Answer

Instead of readAsDataURL, you should use readAsText, so that you get the text instead of a blob.

handleFileUpload() {
          this.file = this.$refs.file.files[0];
          let reader = new FileReader();

          reader.addEventListener("load", function() {
            this.html = reader.result;
          }.bind(this), false);

          reader.readAsText(this.file);
        },
Categories
discuss

Adding in a scroll button with Ionic React

I’m trying to add in a button which scrolls to the top of the page, using Ionic React. This is part of my code so far –

...
function scrollToTop() {
    return document.getElementById("page")!.scrollTop;
}

const Home: React.FC = () => {
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
            <IonButtons slot="start">
                <IonMenuButton />
            </IonButtons>
            <IonTitle slot="end">Ionic Template - JB</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent id={"page"}>
        <IonCard  className="welcomeImage">
            <img src="/assets/welcomeBacking.jpg" alt=""/>
            <IonCardHeader>
                <IonCardTitle>Welcome!</IonCardTitle>
                <IonCardSubtitle>To this Ionic Template</IonCardSubtitle>
            </IonCardHeader>
            <IonCardContent>
                Lorem ipsum........
            </IonCardContent>
        </IonCard>
        {/*Checklist*/}
        <IonList>
            {form.map(({val, isChecked, isDisabled}) => (
                <IonItem key={val}>
                    <IonLabel>{val}</IonLabel>
                    <IonCheckbox slot={"start"} value={val} checked={isChecked} disabled={isDisabled} />
                </IonItem>
                ))}
        </IonList>
          <IonButton onClick={scrollToTop}>Scroll to top</IonButton>
      </IonContent>
    </IonPage>
  );
};

The scrollToTop function should scroll to the to the top of the element with id ‘page’ but tis doesn’t. I don’t get any errors when clicking the button, instead nothing at all happens.

I know this is a trivial thing to implement in Angular but I’m having trouble using React for this. Any help would be great thanks.

Answer

You can do this with scrollToTop method of IonContent, but you have to enable scrollEvents first. In ionic react, the methods can be accessed using refs. Doesn’t look much reacty but at least this works for now.

........    
import React, {useRef} from 'react';

const Home: React.FC = (props) => {
    const contentRef = useRef<HTMLIonContentElement | null>(null);
    const scrollToTop= () => {
        contentRef.current && contentRef.current.scrollToTop();
    };
    return (
        .....
        <IonContent ref={contentRef} scrollEvents={true}>
            ................
            <IonButton onClick={()=>scrollToTop()}>Scroll to top</IonButton>
        </IonContent>
        .....
    );
};
Categories
discuss

Couldn’t able to generate coverage report by aggregating all the modules

Error:

[ERROR] Failed to execute goal org.jacoco:jacoco-maven-plugin:0.8.5:report-aggregate (report-aggregate) on project distribution: Unable to parse configuration of mojo org.jacoco:jacoco-maven-plugin:0.8.5:report-aggregate for parameter dataFileIncludes: Cannot assign configuration entry 'dataFileIncludes' with value '**/jacoco-unit.exec' of type java.lang.String to property of type java.util.List -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.

pom.xml

          <plugin>
               <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.2</version>
                <executions>
                    <execution>
                        <id>report-aggregate</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report-aggregate</goal>
                        </goals>
                        <configuration>
                            <dataFileIncludes>**/jacoco-unit.exec</dataFileIncludes>
                            <outputDirectory>${project.reporting.outputDirectory}/jacoco-aggregate</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

I couldn’t able to aggregate all modules and generate a single code coverage report

Did anyone face this issue? what’s wrong in the pom.xml?

Answer

The error says that the dataFileIncludes is supposed to be a list. This is also defined in jacoco maven plugin source code.

So you can try to map it to the list by following this document:

          <plugin>
           <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.2</version>
            <executions>
                <execution>
                    <id>report-aggregate</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>report-aggregate</goal>
                    </goals>
                    <configuration>
                        <dataFileIncludes>
                           <dataFileInclude>**/jacoco-unit.exec</dataFileInclude> 
                        </dataFileIncludes>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-aggregate</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
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..