Error while trying to access files in the app - android

I'm building a react-native app that uses tensorflow to recognize images, I'm following the steps in this tutorial.
I did everything according to the explanations, including the part of "Fetching files". I created the assets folder and put the files in it (the path is correct).
But when I run this code:
const tfImageRecognition = new TfImageRecognition({
model: require('./assets/tensorflow_inception_graph.pb'),
labels: require('./assets/tensorflow_labels.txt'),
});
The app gives the following error:
I already tried to create a new project, I imported the react-native-tensorflow import { TfImageRecognition } from 'react-native-tensorflow';, I updated the cache, I deleted the folder node_modules and also I created the file "rn-cli.config.js" that is requested in the tutorial to give access to the files in the assets folder. Any idea how to fix this?
I'm using expo to run the app on mobile (android).
npm: 5.51
expo: 51.4.0
react-native: 0.54.0
react-native-cli: 2.0.1

This problem didn't occur with me. Try react-native start --reset-cache and then run the app again.

There is a better way to this.
import model from './assets/tensorflow_inception_graph.pb';
import labels from './assets/tensorflow_labels.txt';
const tfImageRecognition = new TfImageRecognition({
model,
labels
});
Restart your server.

I tried the same example as you mentioned I got accessed Image and Text.
I stored files inside assets in the same directory. Can you share code to produce an error that you faced?
async recognizeImage() {
try {
const tfImageRecognition = new TfImageRecognition({
model:require('./assets/tensorflow_inception_graph.pb'),
labels: require('./assets/tensorflow_labels.txt')
})
const results = await tfImageRecognition.recognize({
image: this.image
})
const resultText = `Name: ${results[0].name} - Confidence: ${results[0].confidence}`
this.setState({result: resultText})
await tfImageRecognition.close()
} catch(err) {
alert(err)
}
}
As you mentioned your using expo then I'm assuming that run npm eject already. As react-native-tensorflow this library require native changes

You must add extensions in your rn-cli.config.js, in order to require tensorflow_inception_graph.pb and tensorflow_labels.txt
module.exports = {
getAssetExts() {
return ['pb', 'txt']
}
}

Replace ./ with so ../ , so final code will be -
model: require('../assets/tensorflow_inception_graph.pb'),
labels: require('../assets/tensorflow_labels.txt')

Related

How to install a downloaded .apk with React Native Expo?

I need to install downloaded .apk file from within the Expo app (it's for update functionality). This is my code:
import React from "react";
import { Button, View } from "react-native";
import * as FileSystem from "expo-file-system";
import { startActivityAsync } from "expo-intent-launcher";
export function Updater() {
async function updateApk() {
const uri = "https://expo.dev/artifacts/eas/my_apk_name.apk";
const localUri = FileSystem.documentDirectory + "test.apk";
try {
await FileSystem.downloadAsync(uri, localUri);
await startActivityAsync("android.intent.action.INSTALL_PACKAGE", {
data: localUri,
flags: 1,
});
} catch (error) {
alert(`Error during installing APK: ${error}`);
}
}
return (
<View>
<Button title="Reset APK" onPress={updateApk} />
</View>
);
}
It downloads the file, stores it, but then there is an error during startActivityAsync:
Encountered an exception while calling native method:
Exception occurred while executing exported method startActivity on module ExpoIntentLauncher:
file://data/user/0/com.my.app.id/files/test.apk exposed beyond app through Intent.getData()
I tried passing uri first to FileSystem.getContentUriAsync() but then there is no error, the intent result is 0 but nothing happens.
My permissions in app.json:
"permissions": [
"READ_EXTERNAL_STORAGE",
"WRITE_EXTERNAL_STORAGE",
"CAMERA"
]
Do I need any additional permissions to get it to work? Or is it completely impossible with Expo? Maybe I should save the file to different location to be able to use this intent?
I also tried android.intent.action.VIEW with no luck.
I test it on Android 13, on physical device. App is built with EAS.
Maybe you can use this command to build release build.
expo:build android
For that you have to signup in Expo's website.
After that you can get apk in Expo's server.
I finally got it to work. The funny part is that I got the answer from the AI that is now banned here. But I just tested this solution on a real android device and it works. Anyway there are two changes needed:
REQUEST_INSTALL_PACKAGES must be added to app.json file.
Uri for intent must be a content uri so: localUri = await FileSystem.getContentUriAsync(localUri)

Url Launcher does not work with MissingPluginException Flutter

I am trying to launch a url in my flutter application. What i'm trying to do is very simple and it works in all other projects except for this one! The browser should be launched on an inkwell onTap event. I tried the exact same code in other projects and worked. I also tried to create a new flutter project and the code worked.
The app does not crash and i don't get any error but on Debug i get a missing plugin exception.
I tried flutter clean and flutter run but didn't work! I tried invalidating cache and restart but also didn't work! I tried removing and re installing the plugin but also didn't work!
Here's the code:
_launchMapsUrl() async {
final url = 'https://www.google.com';
if (await canLaunch(url)) {
await launch(url);
} else {
print('Could not launch $url');
}
}
the onTap:
onTap: () {
_launchMapsUrl();
},
The Compiled and Target SDK versions are 29 and the version of the launcher in my pubspec.yaml is url_launcher: ^5.7.10
For the record the other projects that the code worked in are of the same versions
I think it has something to do with caching issue i'm not really sure, i'm very new to flutter.
Can you please recommend a solution.

Why won't expo-updates provide checkForUpdateAsync?

When I transitioned to Expo's Managed Workflow (SDK 37 and now 38 as well), in-app update checking broke.
My code:
import * as Updates from 'expo-updates';
async checkForUpdate() {
const update = await Updates.checkForUpdateAsync();
if (update.isAvailable) {
this.updateApp();
}
}
async updateApp() {
await Updates.fetchUpdateAsync();
Updates.reloadAsync();
}
Logcat shows me that the checkForUpdateAsync() promise is being rejected with this message:
Error: The method or property Updates.checkForUpdateAsync is not available on android, are you sure you’ve linked all the native dependencies properly?
For the record I did install it via expo install expo-updates
Thanks.
I solved this by creating a new Expo project and looking for differences from my many-times-upgraded one. I found two:
I was using off-the-shelf React Native instead of the Expo build, so I changed the dependency in package.json to "react-native": "https://github.com/expo/react-native/archive/sdk-38.0.1.tar.gz"
I also updated my expo version to ^38.0.8, as used by the new project.
Finally, I also deleted some build relics that I had generated during the way, but I think the fix came from one of the steps above.

How can I generate an AndroidManifest.xml from an existing react-native project?

I already have a react-native app created and I wanna access the user's geolocation. Well, I don't have any Android's folder and I need to add some permissions in AndroidManifest.xml. How can I tie this into my existing project?
Obs: I am using expo and npm.
AndroidManifest.xml not possible with an Expo project. In order to add this permission, you would have to use the Bare workflow
If not you can eject your project from expo or create a new project with react-native-cli and move your source code to it.
Hope this helps you. Feel free for doubts.
Expo has evolved quite a bit in recent years and you can now (Expo SDK 41+) use config plugins to change your AndroidManifest.xml and still remain in the managed workflow. You will lose the ability to use the Expo Go App, but you can use EAS builds to build a custom dev client, which is basically a version of Expo Go tailored to your project.
The docs provide an example of how to use the withAndroidManifest mod to modify permissions. Note that you can run expo prebuild --no-install to test the effects of your plugin, but be sure to delete the generated native folders before running the EAS build, otherwise EAS will assume bare workflow.
The below codes worked for me!
state = {
isLoading:false,
location:null,
errorMessage:null,
isDevice:"",
}
async componentDidMount() {
if (Platform.OS === 'android' && !Constants.isDevice) {
this.setState({
errorMessage:"oops, this will not work on sketch in an android emulator.Try it on your device!"
});
} else {
this._getLocationAsync();
}
}
_getLocationAsync = async () => {
let { status} = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
this.setState({
setError:'Permission to access location was denied'
});
}
let location = await Location.getCurrentPositionAsync({});
this.setState({
location
})
console.log(location)
}
It is possible to edit AndroidManifest.xml with apktool, followed by using apksigner to re-sign the apk with credentials from expo credentials:manager.
To edit the existing manifest:
apktool decode myapp-original.apk
vim myapp-original/AndroidManifest.xml
To re-build a new signed apk:
apktool build myapp-original -o myapp.apk
expo credentials:manager -p android
/path/toAndroid/Sdk/build-tools/$VERSION/apksigner sign -ks #username__myapp.bak.jks myapp.apk

How to use svg images on react-native?

I'm trying to use svg images on my native react application, I'm developing on Android.
So I followed this tutorial =>
https://medium.com/faun/add-custom-svg-icons-to-your-expo-app-279b492f6a15
I have an error Unable to read the 'fill' property of undefined while I manage to display the image, so I try to downgrade the version of react-native- svg and the image is displayed but as soon as I integrated react-navigation my application expo on crash at startup.
So I looked for a long time for the cause of this crash.
I tried to delete the react-native-svg library, the metroconfig.js file, and expo worked again, I don't know if this was the cause of the problem.
I would like to know if people have encountered these problems or if not what is the best method which works with the current version of RN to import a svg image in a react-native application?
Thank you in advance for your help and your answers.
EDIT
I tested react-native-svg and react-native-transformer-svg with the latest version of react native / expo / sdk expo
From the moment I create the metro.config.js file and link it with expo by updating the app.json file, my expo application crashes at startup.
I had to use react-native-svg without react-native-transformer-svg, that is to say that I have to convert an SVG file into a reactable SVG file.
If someone has a working solution to import svg files automatically, it would be of great help to me.
Important Note - I develop on a real Android device, not in Expo!
Here is some code from an issue opened on Github that actually worked for me after some modification.
Link to Github issue
In my metro.config.js file I finally have this code:
const { getDefaultConfig } = require("metro-config")
module.exports = (async () => {
const {
resolver: { sourceExts, assetExts },
} = await getDefaultConfig()
// here I extend the extensions needed for RN because I use JSX.
// you don't need this if you use pure JS files
const updatedSourceExts = [...sourceExts, "jsx", "js", "json", "ts", "tsx"]
return {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
babelTransformerPath: require.resolve("react-native-svg-transformer"),
},
resolver: {
assetExts: assetExts.filter((ext) => ext !== "svg"),
sourceExts: [...updatedSourceExts, "svg"],
},
}
})()
A part of my package-json file:
"react-native": "0.63.2",
"react-native-svg": "^12.1.0",
"react-native-svg-transformer": "^0.14.3"
Install react-native-svg-transformer
npm i react-native-svg-transformer --save
I'm using SVG as following and it works fine
import LOGOSVG from "assets/svg/logo.svg"
in render
<View>
<LOGOSVG
width="100%"
height="70%"
/>
</View>

Categories

Resources