Showing posts with label react-native. Show all posts
Showing posts with label react-native. Show all posts

react-native : header bar(title + option button) example

Render

   render() {
      return (
        <View style={styles.container}>
          <View style={styles.header}>
            <Text style={styles.title}>
              {I18n.t('wcsqa')} // your title
            </Text>
            <TouchableOpacity onPress={() => {}}>
              <Image
                style={styles.option}
                source={require('./res/img/nav_icon.png')}
              />
            </TouchableOpacity>
          </View>
          <View style={styles.content}>
            <Text>
              {this.wcs[0].Q} // your content
            </Text>
          </View>
        </View>
      )
  }

Style

const styles = StyleSheet.create({
  container: {
    flex: 2,
  },
  header: {
    backgroundColor: '#00FF7F',
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold'
  },
  option: {
    width:32,
    height:32
  },
  content: {
    backgroundColor: '#F5DEB3',
    flex: 12
  }
});

No Image, No Truth

header-bar

react-native run-android : Unable to process incoming event ‘ProgressComplete ’ (ProgressCompleteEvent) on Windows

Error

Unable to process incoming event 'ProgressComplete ' (ProgressCompleteEvent) on Windows

Solution

I looked solution from web, but not found one can work for my issue.
https://github.com/gradle/gradle/issues/882
Then I just closed my shell window(cmd.exe or powershell.exe) and reopen a new one,
I found the issue gone.

react-native : full screen background image example

render

render() {
  return (
    <ImageBackground
       style={styles.bgimg}
       source={require('./res/img/wcs.png')}>
      <View style={styles.fgcontainer}>
        <Text style={styles.qa}>
           WCS WCS WCS
        </Text>
      </View>
    </ImageBackground>
  );
}

Style

const styles = StyleSheet.create({
  bgimg: {
    flex: 1
  },
  fgcontainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  qa: {
    fontSize: 30,
    fontWeight: 'bold'
  }
});

No Image, No Truth

wcsfullscreen

react-native : center an Image example

Render

  render() {
    return (
      <View style={styles.splashContainer}>
        <Image
            source={require('./res/img/Catechism-words.png')}>
        </Image>
      </View>
    )
  }

Style

const styles = StyleSheet.create({
  splashContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#00FF7F'
  }
});

No Image, No True

wcsqa

react-native : navigate/load url via WebView

No Image, No Truth

webview-load

use WebView component in reactnative.

var {   ....,   WebView, } = React; 

initial state give a default url

getInitialState: function() {  return {   url: '', // or default url  }; }, 

render with state url

<WebView ....your styles, properties   url={this.state.url} /> 

Navigate/load codes

load() {  this.setState({url:'http://google.com'}); } 

Full Sample Codes

import React, { Component } from 'react';
import {
Button,
Modal,
Image,
Keyboard,
NativeModules,
Platform,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
WebView,
} from 'react-native';

const { WeChat } = NativeModules;

const SHARE_TO_WXTIMELINE = 0;
const SHARE_TO_WXSESSION = 1;
const webview = "webview";
const HOME_URL = "https://errong.win";

export default class App extends Component<{}> {

componentWillMount () {
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {this.keyboardDidHide()});
}

componentWillUnmount () {
this.keyboardDidHideListener.remove();
}

keyboardDidHide () {
console.log( this.urlText );
if (this.urlText != null) {
this.setState({url:this.urlText});
}
}

constructor(props) {
super(props);
this.state = {shareModalVisible : false, url : HOME_URL, urlBarVisible : true};
}

setShareModalVisible(visible) {
this.setState({shareModalVisible : visible});
}

onShare(scene) {
this.setShareModalVisible(false);
this.scene = scene;
if (this.shareMsg == null)
return;
if (WeChat.shareToTimeline)
WeChat.shareToTimeline(this.shareMsg, this.scene, null);
}

onWebViewMessage(event) {
console.warn(event.nativeEvent.data);
let msg;
try {
msg = JSON.parse(event.nativeEvent.data);
} catch (err) {
console.warn(err);
return;
}
if (msg.id == "ABSTRACT_FETCHED")
this.shareMsg = msg;
}

genAbstractJS() {
const genAbstractFunction = function() {
try {
let title;
let description;
let imageUrl;
let msg;
let n = document.querySelector('head title');
if (n)
title = n.innerText;
n = document.querySelector('p');
if (n)
description = n.innerText;
n = document.querySelector('p img');
if (n)
imageUrl = n.src;
if (description && imageUrl) {
msg = { 'id' : 'ABSTRACT_FETCHED',
'type' : 'textimage',
'description' : description,
'imageUrl': imageUrl
};
} else {
msg = { 'id' : 'ABSTRACT_FETCHED',
'type' : 'news',
'webpageUrl' : window.location.href
};
}
window.postMessage(JSON.stringify(msg), "*");
} catch (err) {
console.warn(err);
}
}
let js = "(" + String(genAbstractFunction) + ")();";
console.log(js);
return js;
}

onLoadEnd() {
this.refs[webview].injectJavaScript(this.genAbstractJS());
}

onUrlBar() {
}

renderUrlBar() {
if (this.state.urlBarVisible) {
return (
<TouchableOpacity style={styles.urlbar} onPress={() => {this.onUrlBar()}}>
<TextInput
style={styles.urlentry}
placeholder="search or input url"
onChangeText={(text) => {this.urlText = text}}
/>

)
} else {
return null;
}
}

render() {
return (

{this.renderUrlBar()}
<WebView
ref={webview}
style={{flex:1}}
javaScriptEnabled={true}
onMessage={(event) => {this.onWebViewMessage(event)}}
onLoadEnd={this.onLoadEnd.bind(this)}
source={{uri:this.state.url}}
/>
<Button
onPress={() => {this.setShareModalVisible(true)}}
title="Share"
color="#841584"
accessibilityLabel="Social Share"
/>



<TouchableOpacity style={styles.sharebutton} onPress={() => {this.onShare(SHARE_TO_WXTIMELINE)}}>
<Image
source={require('./res/img/wxtimeline.png')}
/>

<TouchableOpacity style={styles.sharebutton} onPress={() => {this.onShare(SHARE_TO_WXSESSION)}}>
<Image
source={require("./res/img/wxsession.png")}
/>





);
}
}

const styles = StyleSheet.create({
urlbar:{
backgroundColor:'#fafad2',
borderTopLeftRadius:4,
borderTopRightRadius:4,
borderBottomLeftRadius:4,
borderBottomRightRadius:4,
boderColor : '#C0C0C0',
borderWidth: 1
},
urlentry:{
height: 40
},
sgc:{
height:100,
width:300,
borderTopLeftRadius:10,
borderTopRightRadius:10,
borderBottomLeftRadius:10,
borderBottomRightRadius:10,
alignSelf: 'center',
top:400,
backgroundColor:'#fafad2'
},
sharegroup: {
flex:1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
},
sharebutton: {
width:64,
height:64
}
})

react-native : Modal example, share to WeChat

Refer

https://facebook.github.io/react-native/docs/modal.html

No Image, No Truth

modal-share

Full Codes

import React, { Component } from 'react'; import {     Button, 	Modal,     Image,     Keyboard,     NativeModules,     Platform,     StyleSheet,     Text,     TextInput,     TouchableOpacity,     View,     WebView, } from 'react-native';  const { WeChat } = NativeModules;  const SHARE_TO_WXTIMELINE = 0; const SHARE_TO_WXSESSION = 1; const webview = "webview"; const HOME_URL = "https://errong.win";  export default class App extends Component<{}> {    componentWillMount () {     this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {this.keyboardDidHide()});   }    componentWillUnmount () {     this.keyboardDidHideListener.remove();   }    keyboardDidHide () {     console.log( this.urlText );     if (this.urlText != null) {       this.setState({url:this.urlText});     }   }    constructor(props) {     super(props);     this.state = {shareModalVisible : false, url : HOME_URL, urlBarVisible : true};   }    setShareModalVisible(visible) {     this.setState({shareModalVisible : visible});   }    onShare(scene) {     this.setShareModalVisible(false); 	this.scene = scene;     if (this.shareMsg == null)       return;     if (WeChat.shareToTimeline)       WeChat.shareToTimeline(this.shareMsg, this.scene, null);   }    onWebViewMessage(event) {     console.warn(event.nativeEvent.data);     let msg;     try {       msg = JSON.parse(event.nativeEvent.data);     } catch (err) {       console.warn(err);       return;     }     if (msg.id == "ABSTRACT_FETCHED")       this.shareMsg = msg;   }    genAbstractJS() {     const genAbstractFunction = function() {       try {         let title;         let description;         let imageUrl;         let msg;         let n = document.querySelector('head title');         if (n)             title = n.innerText;         n = document.querySelector('p');         if (n)             description = n.innerText;         n = document.querySelector('p img');         if (n)             imageUrl = n.src;         if (description && imageUrl) {             msg = { 'id' : 'ABSTRACT_FETCHED',                     'type' : 'textimage',                     'description' : description,                     'imageUrl': imageUrl                   };         } else {            msg = { 'id' : 'ABSTRACT_FETCHED',                    'type' : 'news',                    'webpageUrl' : window.location.href                  };         }         window.postMessage(JSON.stringify(msg), "*");       } catch (err) {         console.warn(err);       }     }     let js = "(" + String(genAbstractFunction) + ")();";     console.log(js);     return js;   }    onLoadEnd() {     this.refs[webview].injectJavaScript(this.genAbstractJS());   }    onUrlBar() {   }    renderUrlBar() {     if (this.state.urlBarVisible) {       return (         <TouchableOpacity style={styles.urlbar} onPress={() => {this.onUrlBar()}}>           <TextInput             style={styles.urlentry}             placeholder="search or input url"             onChangeText={(text) => {this.urlText = text}}           />         </TouchableOpacity>       )     } else {       return null;     }   }    render() {     return (     <View style={{flex:1}}>       {this.renderUrlBar()}       <WebView         ref={webview}         style={{flex:1}}         javaScriptEnabled={true}         onMessage={(event) => {this.onWebViewMessage(event)}}         onLoadEnd={this.onLoadEnd.bind(this)}         source={{uri:this.state.url}}       />       <Button         onPress={() => {this.setShareModalVisible(true)}}         title="Share"         color="#841584"         accessibilityLabel="Social Share"       /> 	  <Modal 		transparent={true} 		visible={this.state.shareModalVisible} 		> 		<View style={styles.sgc}>           <View style={styles.sharegroup}>             <TouchableOpacity style={styles.sharebutton} onPress={() => {this.onShare(SHARE_TO_WXTIMELINE)}}>               <Image                 source={require('./res/img/wxtimeline.png')}               />             </TouchableOpacity>             <TouchableOpacity style={styles.sharebutton} onPress={() => {this.onShare(SHARE_TO_WXSESSION)}}>               <Image                 source={require("./res/img/wxsession.png")}               />             </TouchableOpacity>           </View> 		</View> 	  </Modal>     </View>     );   } }  const styles = StyleSheet.create({   urlbar:{   	backgroundColor:'#fafad2',     borderTopLeftRadius:4,     borderTopRightRadius:4,     borderBottomLeftRadius:4,     borderBottomRightRadius:4,     boderColor : '#C0C0C0',     borderWidth: 1   },   urlentry:{     height: 40   },   sgc:{   	height:100,     width:300,     borderTopLeftRadius:10,     borderTopRightRadius:10,     borderBottomLeftRadius:10,     borderBottomRightRadius:10,     alignSelf: 'center',   	top:400,   	backgroundColor:'#fafad2'   },   sharegroup: {   	flex:1, 	flexDirection: 'row',   	alignItems: 'center',   	justifyContent: 'space-around',   },   sharebutton: {     width:64,     height:64   } }) 

react-native : How to create Image Button

Solution

Use TouchableOpacity, Image and Styles.

Key codes

import React, { Component } from 'react'; import {         Image,     StyleSheet,        TouchableOpacity, } from 'react-native';  <TouchableOpacity     style={styles.sharebutton}     onPress={() => {this.onShare(SHARE_TO_WXTIMELINE)}} >     <Image         source={require('./res/img/wxtimeline.png')}     /> </TouchableOpacity>          

No Image, No Truth

modal-share
See Full sample codes Share to WeXin via Modal

react-native : Native Modules, name prefix "RCT"works for android too

I tried to export wechat sdk as a native module.
I copied some codes here:
public class WeChatModule extends ReactContextBaseJavaModule implements IWXAPIEventHandler {
  private String appId; 
  public WeChatModule(ReactApplicationContext context) { 
    super(context); 
  @Override     public String getName() { 
    return "RCTWeChat"; 
} 
I used "RCTWeChat" as the module name, I did not know the "RCT" prefix meanings.

ReactContextBaseJavaModule requires that a method called getName is implemented. The purpose of this method is to return the string name of the NativeModule which represents this class in JavaScript.

Then I encountered error in my react-native JS codes.
import {NativeModules} from 'react-native'; const { RCTWeChat } = NativeModules; 
WeChat or NativeModules.RCTWeChat always undefined.

Cause

RCT is a prefix used in react native, it will be removed when exported to JS.
React Native uses RCT as a prefix. In order to avoid name collisions, we recommend using a three-letter prefix other than RCT in your own classes.

Solution

The correct JS codes:
const { WeChat } = NativeModules;

react-native run-android : No connected devices!

  • What went wrong:
    Execution failed for task ':app:installDebug'.

com.android.builder.testing.api.DeviceException: No connected devices!

Cause

ADB driver is not ready

Solution

Install correct driver
adb

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

F:\webrowser>react-native run-android
Scanning folders for symlinks in F:\webrowser\node_modules (73ms)
Starting JS server...
Building and installing the app on the device (cd android && gradlew.bat install
Debug)...
Downloading https://services.gradle.org/distributions/gradle-4.1-all.zip
Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.val
idator.ValidatorException: PKIX path building failed: sun.security.provider.cert
path.SunCertPathBuilderException: unable to find valid certification path to req
uested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1959)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.
java:1514)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.jav
a:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1072)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.
java:1385)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413
)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397
)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:
559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect
(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLCo
nnection.java:1564)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLCon
nection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Http
sURLConnectionImpl.java:263)
at org.gradle.wrapper.Download.downloadInternal(Download.java:58)
at org.gradle.wrapper.Download.download(Download.java:44)
at org.gradle.wrapper.Install$1.call(Install.java:59)
at org.gradle.wrapper.Install$1.call(Install.java:46)
at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAcc
essManager.java:65)
at org.gradle.wrapper.Install.createDist(Install.java:46)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:126)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find vali
d certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:397)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.jav
a:302)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.j
ava:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerIm
pl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustMan
agerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.
java:1496)
... 20 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBu
ilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCert
PathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392)
... 26 more
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

Cause

java client try to downloading https resources without valid certification.

Solution

  1. Downloading <a href="http://pwpan.com/fs/4leeng7er4ro9ng0e57/" target="_blank">InstallCert.java</a>
  2. Compile
    javac InstallCert.java
  3. Run InstallCert and get certs from the host.
    my failed resource is
    https://services.gradle.org/distributions/gradle-4.1-all.zip
    the host is services.gradle.org
    java InstallCert services.gradle.org
    If everything works well, you will get a file named jssecacerts.
c:\Users\Administrator\Desktop>java InstallCert services.gradle.org
Loading KeyStore C:\Program Files\Java\jdk1.8.0_152\jre\lib\security\cacerts...
Opening connection to services.gradle.org:443...
Starting SSL handshake...
......
Server sent 3 certificate(s):
1 Subject CN=ssl473435.cloudflaressl.com, OU=PositiveSSL Multi-Domain, OU=Domain Control Validated
Issuer CN=COMODO ECC Domain Validation Secure Server CA 2, O=COMODO CA Limited, L=Salford, ST=Greater Manchester, C=GB
sha1 d4 e8 9d a9 2c 27 22 1f 63 a9 33 d8 ca 98 01 3d 02 6c 59 ea
md5 ba 64 ca 8d 7f ab d8 8e f2 e0 d3 79 79 51 96 30
2 Subject CN=COMODO ECC Domain Validation Secure Server CA 2, O=COMODO CA Limited, L=Salford, ST=Greater Manchester, C=GB
Issuer CN=COMODO ECC Certification Authority, O=COMODO CA Limited, L=Salford, ST=Greater Manchester, C=GB
sha1 75 cf d9 bc 5c ef a1 04 ec c1 08 2d 77 e6 33 92 cc ba 52 91
md5 5e 0e 41 9b 20 ea 57 54 77 f1 1b 52 e2 c8 18 e0
3 Subject CN=COMODO ECC Certification Authority, O=COMODO CA Limited, L=Salford, ST=Greater Manchester, C=GB
Issuer CN=AddTrust External CA Root, OU=AddTrust External TTP Network, O=AddTrust AB, C=SE
sha1 ae 22 3c bf 20 19 1b 40 d7 ff b4 ea 57 01 b6 5f dc 68 a1 ca
md5 c7 90 a5 6c 69 cb af 0b f3 f3 0a 40 d0 a2 ae cc
Enter certificate to add to trusted keystore or 'q' to quit: [1]
1 // enter 1 here
......
Added certificate to keystore 'jssecacerts' using alias 'services.gradle.org-1'
  1. copy jssecacerts to jre security folder
    cp jssecacerts $JAVA_HOME/jre/lib/security/jssecacerts

Issue fiexed

gradle-4.1-all.zip is downloading
downloadinggradle

react-native : communicate between react-native JS and WebView component

APIs:

window.postMessage in WebView, post a message to react-native JS.
onMessage callback in react-native JS, receive a message from WebView.
injectjavascript, Function that accepts a string that will be passed to the WebView and executed immediately as JavaScript.
injectedjavascript, Set this to provide JavaScript that will be injected into the web page when the view loads.
onMessage
A function that is invoked when the webview calls window.postMessage. Setting this property will inject a postMessage global into your webview, but will still call pre-existing values of postMessage.
window.postMessage accepts one argument, data, which will be available on the event object, event.nativeEvent.data.

data must be a string.

Sample code

import React, { Component } from 'react';
import {
  Button,
  Platform,
  StyleSheet,
  Text,
  View,
  WebView,
} from 'react-native';

var WEBVIEW_REF = 'webview';

export default class App extends Component<{}> {
  constructor(props) {
    super(props);
    this.onWebViewMessage = this.onWebViewMessage.bind(this);
    this.onShare = this.onShare.bind(this);
  }

  onWebViewMessage(event) {
    console.warn(event.nativeEvent.data);
    let msg;
    try {
      msg = JSON.parse(event.nativeEvent.data);
    } catch (err) {
      console.warn(err);
      return;
    }
    console.log(msg);
  }

  onShare() {
    var fetchAbstractJS = "(" + this.fetchAbstract.toString() + "());";
    console.log(fetchAbstractJS);
    this.refs[WEBVIEW_REF].injectJavaScript(fetchAbstractJS);
  }

  // function called in WebView via injectJavaScript
  fetchAbstract() {
    try {
      var title = document.querySelector('head title').innerText;
      var desc = document.querySelector('p').innerText;
      var imgurl = document.querySelector('p img').src;
      // post Message to react-native JS
      window.postMessage(JSON.stringify({'id' : 'ABSTRACT_FETCHED', 'url' : window.location.href, 'title' : title, 'desc' : desc, 'imgurl' : imgurl}), "*");
    } catch (err) {
      console.warn(err);
      return;
    }
  }

  render() {
    return (
    <View style={{flex:1}}>
      <WebView
        ref={WEBVIEW_REF}
        style={{flex:1}}
        onMessage={this.onWebViewMessage}
        source={{uri: 'https://manna.errong.win/let-s-growing-up-in-jesus/'}}
      />
      <Button
        onPress={this.onShare}
        title="Share"
        color="#841584"
        accessibilityLabel="Social Share"
      />
    </View>
    );
  }
}

react-native log-android

log-android

Refer

https://facebook.github.io/react-native/docs/webview.html#onmessage
https://facebook.github.io/react-native/docs/webview.html#injectjavascript
https://facebook.github.io/react-native/docs/webview.html#injectedjavascript

react-native run-android : Command `run-android` unrecognized

F:\webrowser>react-native run-android
Command run-android unrecognized. Make sure that you have run npm install an
d that you are inside a react-native project.

F:\webrowser>npm install
added 781 packages in 338.768s

npm ERR! code UNABLE_TO_VERIFY_LEAF_SIGNATURE

F:\webrowser>npm install -g react-native-cli
npm ERR! code UNABLE_TO_VERIFY_LEAF_SIGNATURE
npm ERR! errno UNABLE_TO_VERIFY_LEAF_SIGNATURE
npm ERR! request to https://registry.npmjs.org/react-native-cli failed, reason:
unable to verify the first certificate

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Administrator\AppData\Roaming\npm-cache_logs\2018-01-11T1
6_55_54_266Z-debug.log

solution

npm config set strict-ssl false

F:\webrowser>npm install -g react-native-cli
C:\Users\Administrator\AppData\Roaming\npm\react-native -> C:\Users\Administrato
r\AppData\Roaming\npm\node_modules\react-native-cli\index.js

  • react-native-cli@2.0.1
    added 41 packages in 23.687s

Generate Signed android APK for react-native app

Refer:
https://facebook.github.io/react-native/docs/signed-apk-android.html

create your own key store file

https://errong.win/generate-keystore/

modifications

signed-apk

error INSTALL_FAILED_UPDATE_INCOMPATIBLE

https://errong.win/react-native-run-android-variant-release/

java.lang.NullPointerException (no error message)

When I set below values to true, I encountered NullPointerException.
so my reset them to false again.

+ def enableSeparateBuildPerCPUArchitecture = true + universalApk true  // If true, also generate a universal APK + def enableProguardInReleaseBuilds = true 

error can't delete/read lint-results-release-fatal.html

kill all java.exe via task manager

react-native run-android --variant=release INSTALL_FAILED_UPDATE_INCOMPATIBLE

Task :app:installRelease
Installing APK 'app-release.apk' on 'Nexus_5X_API_23(AVD) - 6.0' for app:release
Unable to install C:\Users\lenger\Desktop\webrowser\android\app\build\outputs\apk\release\app-release.apk
com.android.ddmlib.InstallException: INSTALL_FAILED_UPDATE_INCOMPATIBLE
at com.android.ddmlib.Device.installRemotePackage(Device.java:1004)
at com.android.ddmlib.Device.installPackage(Device.java:911)
at com.android.builder.testing.ConnectedDevice.installPackage(ConnectedDevice.java:122)
at com.android.build.gradle.internal.tasks.InstallVariantTask.install(InstallVariantTask.java:171)
at com.android.build.gradle.internal.tasks.InstallVariantTask.install(InstallVariantTask.java:105)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.doExecute(DefaultTaskClassInfoStore.java:141)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:731)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:705)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':app:installRelease'.

com.android.builder.testing.api.DeviceException: com.android.ddmlib.InstallException: INSTALL_FAILED_UPDATE_INCOMPATIBLE

Cause

the application which you want to install is already installed.

Solution

uninstall the old one and try again.
adb uninstall xxx

react-native run-android : do not build/update modified code(App.js)

Solution

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res 

c:\Users\lenger\Desktop\webrowser>react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
Scanning folders for symlinks in c:\Users\lenger\Desktop\webrowser\node_modules (43ms)
Scanning folders for symlinks in c:\Users\lenger\Desktop\webrowser\node_modules (38ms)
Loading dependency graph, done.
bundle: start
bundle: finish
bundle: Writing bundle output to: android/app/src/main/assets/index.android.bundle
bundle: Done writing bundle output

Run react-native run-android again, you will find your modification work.

react-native run-android : Could not find com.android.tools.build:gradle:3.0.1

Could not resolve all files for configuration ':classpath'.
Could not find com.android.tools.build:gradle:3.0.1.
Searched in the following locations:
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.pom
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.jar
Required by:
project :

Solution

Add google() inside buildscript() and Sync Project.
gradle-issues

react-native run-android : buildToolsVersion "23.0.1" is ignored

c:\Users\lenger\Desktop\webrowser>git diff android/build.gradle

diff --git a/android/build.gradle b/android/build.gradle index eed9972..c5fecab 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -5,7 +5,7 @@ buildscript {          jcenter()      }      dependencies { -        classpath 'com.android.tools.build:gradle:2.2.3' +        classpath 'com.android.tools.build:gradle:3.0.1'           // NOTE: Do not place your application dependencies here; they belong          // in the individual module build.gradle files 

warning

c:\Users\lenger\Desktop\webrowser>git diff android/app/build.gradle

diff --git a/android/app/build.gradle b/android/app/build.gradle index b589c49..b20457c 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -95,7 +95,6 @@ def enableProguardInReleaseBuilds = false   android {      compileSdkVersion 23 -    buildToolsVersion "23.0.1"       defaultConfig {          applicationId "com.webrowser" 

react-native run-android : Failed to notify project evaluation listener

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':app'.

Failed to notify project evaluation listener.
com.android.build.gradle.tasks.factory.AndroidJavaCompile.setDependencyCacheDir(Ljava/io/File;)V

Open your app via Android Studio, you will get more info to resolve the issue.
gradle-sync-issues
The versions of the Android Gradle plugin and Gradle are not compatible.
Please do one of the following:

  • Update your plugin to version 2.4.
  • Downgrade Gradle to version 3.5.

Create App Icons for React Native Android App

First you need one png file as your launcher icon.
icon
Then you need to resize this icon file to needed resolutions.
There is a simple service to resize your app icon to all needed resolutions with rocket speed.
Then you can download all your needed icons.
icons
Then replace each ic_launcher.png via image with correct resolution.
webrowser/android$ find -name "ic_launcher.png"
./app/src/main/res/mipmap-hdpi/ic_launcher.png
./app/src/main/res/mipmap-mdpi/ic_launcher.png
./app/src/main/res/mipmap-xhdpi/ic_launcher.png
./app/src/main/res/mipmap-xxhdpi/ic_launcher.png

Or you can use Image Asset Studio to create App Icons.
1.open Android Studio poject in your react native application.
open-app
2.use Image Asset Studio
open-image-asset
In the Foreground Layer tab, select an Asset Type, and then specify the asset in the field underneath:
Select Image to specify the path for an image file.

If your app supports Android 8.0, create adaptive and legacy launcher icons.
ic_launcher
If your app supports versions no higher than Android 7.1, create a legacy launcher icon only.
ic_launcher-1

Check the result
react-native run-android

lc

Refer

https://developer.android.com/studio/write/image-asset-studio.html
https://www.npmjs.com/package/react-native-icon

fixed: embedded-redis: Unable to run on macOS Sonoma

Issue you might see below error while trying to run embedded-redis for your testing on your macOS after you upgrade to Sonoma. java.la...