Skip to content

Commit ae6366a

Browse files
committed
add android example
1 parent 570aaa6 commit ae6366a

File tree

7 files changed

+124
-144
lines changed

7 files changed

+124
-144
lines changed

README.md

Lines changed: 1 addition & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -9,66 +9,12 @@ Zip archive utility for react-native
99

1010
```bash
1111
npm install react-native-zip-archive --save
12-
```
13-
14-
## Getting started - iOS
15-
```bash
1612
react-native link react-native-zip-archive
1713
```
1814

19-
## Getting started - Android
20-
21-
* Edit `android/settings.gradle` to look like this (without the +):
22-
23-
```diff
24-
rootProject.name = 'MyApp'
25-
26-
include ':app'
27-
28-
+ include ':react-native-zip-archive'
29-
+ project(':react-native-zip-archive').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-zip-archive/android')
30-
```
31-
32-
* Edit `android/app/build.gradle` (note: **app** folder) to look like this:
33-
34-
```diff
35-
apply plugin: 'com.android.application'
36-
37-
android {
38-
...
39-
}
40-
41-
dependencies {
42-
compile fileTree(dir: 'libs', include: ['*.jar'])
43-
compile 'com.android.support:appcompat-v7:23.0.0'
44-
compile 'com.facebook.react:react-native:0.16.+'
45-
+ compile project(':react-native-zip-archive')
46-
}
47-
```
48-
49-
* Edit your `MainActivity.java` (deep in `android/app/src/main/java/...`) to look like this (note **two** places to edit):
50-
51-
```diff
52-
package com.myapp;
53-
54-
+ import com.rnziparchive.RNZipArchivePackage;
55-
56-
....
57-
58-
@Override
59-
protected List<ReactPackage> getPackages() {
60-
return Arrays.<ReactPackage>asList(
61-
new MainReactPackage(),
62-
+ new RNZipArchivePackage()
63-
);
64-
}
65-
66-
}
67-
```
68-
6915
## Usage
7016

71-
require it in your file
17+
import it into your code
7218

7319
```js
7420
import { zip, unzip, unzipAssets, subscribe } from 'react-native-zip-archive'

android/build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,5 @@ repositories {
3030
}
3131

3232
dependencies {
33-
compile 'com.facebook.react:react-native:0.12.+'
33+
compile "com.facebook.react:react-native:+"
3434
}

android/src/main/java/com/rnziparchive/RNZipArchiveModule.java

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import android.util.Log;
55

66
import com.facebook.react.bridge.Arguments;
7-
import com.facebook.react.bridge.Callback;
7+
import com.facebook.react.bridge.Promise;
88
import com.facebook.react.bridge.ReactApplicationContext;
99
import com.facebook.react.bridge.ReactContextBaseJavaModule;
1010
import com.facebook.react.bridge.ReactMethod;
@@ -43,21 +43,27 @@ public String getName() {
4343
}
4444

4545
@ReactMethod
46-
public void unzip(String zipFilePath, String destDirectory, Callback callback) {
46+
public void unzip(String zipFilePath, String destDirectory, Promise promise) {
4747
FileInputStream inputStream;
4848
File file;
4949
try {
5050
inputStream = new FileInputStream(zipFilePath);
5151
file = new File(zipFilePath);
5252
} catch (FileNotFoundException | NullPointerException e) {
53-
callback.invoke(makeErrorPayload("Couldn't open file " + zipFilePath + ". ", e));
53+
promise.reject(null, "Couldn't open file " + zipFilePath + ". ");
5454
return;
5555
}
56-
unzipStream(zipFilePath, destDirectory, inputStream, file.length(), callback);
56+
try {
57+
unzipStream(zipFilePath, destDirectory, inputStream, file.length());
58+
} catch (Exception ex) {
59+
promise.reject(null, ex.getMessage());
60+
return;
61+
}
62+
promise.resolve(destDirectory);
5763
}
5864

5965
@ReactMethod
60-
public void unzipAssets(String assetsPath, String destDirectory, Callback completionCallback) {
66+
public void unzipAssets(String assetsPath, String destDirectory, Promise promise) {
6167
InputStream assetsInputStream;
6268
long size;
6369

@@ -66,15 +72,21 @@ public void unzipAssets(String assetsPath, String destDirectory, Callback comple
6672
AssetFileDescriptor fileDescriptor = getReactApplicationContext().getAssets().openFd(assetsPath);
6773
size = fileDescriptor.getLength();
6874
} catch (IOException e) {
69-
completionCallback.invoke(makeErrorPayload(String.format("Asset file `%s` could not be opened", assetsPath), e));
75+
promise.reject(null, String.format("Asset file `%s` could not be opened", assetsPath));
7076
return;
7177
}
7278

73-
unzipStream(assetsPath, destDirectory, assetsInputStream, size, completionCallback);
79+
try {
80+
unzipStream(assetsPath, destDirectory, assetsInputStream, size);
81+
} catch (Exception ex) {
82+
promise.reject(null, ex.getMessage());
83+
return;
84+
}
85+
promise.resolve(destDirectory);
7486
}
7587

7688
@ReactMethod
77-
public void zip(String fileOrDirectory, String destDirectory, Callback callback) {
89+
public void zip(String fileOrDirectory, String destDirectory, Promise promise) {
7890
List<String> filePaths = new ArrayList<>();
7991
File file;
8092
try {
@@ -92,14 +104,21 @@ public void zip(String fileOrDirectory, String destDirectory, Callback callback)
92104
throw new FileNotFoundException(fileOrDirectory);
93105
}
94106
} catch (FileNotFoundException | NullPointerException e) {
95-
callback.invoke(makeErrorPayload("Couldn't open file/directory " + fileOrDirectory + ". ", e));
107+
promise.reject(null, "Couldn't open file/directory " + fileOrDirectory + ".");
96108
return;
97109
}
98110

99-
zipStream(filePaths.toArray(new String[filePaths.size()]), destDirectory, filePaths.size(), callback);
111+
try {
112+
zipStream(filePaths.toArray(new String[filePaths.size()]), destDirectory, filePaths.size());
113+
} catch (Exception ex) {
114+
promise.reject(null, ex.getMessage());
115+
return;
116+
}
117+
118+
promise.resolve(destDirectory);
100119
}
101120

102-
private void zipStream(String[] files, String destFile, long totalSize, Callback completionCallback) {
121+
private void zipStream(String[] files, String destFile, long totalSize) throws Exception {
103122
try {
104123
if (destFile.contains("/")) {
105124
File destDir = new File(destFile.substring(0, destFile.lastIndexOf("/")));
@@ -136,11 +155,10 @@ private void zipStream(String[] files, String destFile, long totalSize, Callback
136155
}
137156
updateProgress(1, 1, destFile); // force 100%
138157
out.close();
139-
completionCallback.invoke(null, null);
140158
} catch (Exception ex) {
141159
ex.printStackTrace();
142160
updateProgress(0, 1, destFile); // force 0%
143-
completionCallback.invoke(makeErrorPayload(String.format("Couldn't zip %s", destFile), ex));
161+
throw new Exception(String.format("Couldn't zip %s", destFile));
144162
}
145163
}
146164

@@ -161,7 +179,7 @@ private List<File> getSubFiles(File baseDir, boolean isContainFolder) {
161179
return fileList;
162180
}
163181

164-
private void unzipStream(String zipFilePath, String destDirectory, InputStream inputStream, long totalSize, Callback completionCallback) {
182+
private void unzipStream(String zipFilePath, String destDirectory, InputStream inputStream, long totalSize) throws Exception {
165183
try {
166184
File destDir = new File(destDirectory);
167185
if (!destDir.exists()) {
@@ -195,11 +213,10 @@ private void unzipStream(String zipFilePath, String destDirectory, InputStream i
195213
updateProgress(1, 1, zipFilePath); // force 100%
196214
bin.close();
197215
zipIn.close();
198-
completionCallback.invoke(null, null);
199216
} catch (Exception ex) {
200217
ex.printStackTrace();
201218
updateProgress(0, 1, zipFilePath); // force 0%
202-
completionCallback.invoke(makeErrorPayload(String.format("Couldn't extract %s", zipFilePath), ex));
219+
throw new Exception(String.format("Couldn't extract %s", zipFilePath));
203220
}
204221
}
205222

@@ -235,10 +252,4 @@ private long extractFile(ZipInputStream zipIn, String filePath) throws IOExcepti
235252

236253
return size;
237254
}
238-
239-
private WritableMap makeErrorPayload(String message, Exception ex) {
240-
WritableMap error = Arguments.createMap();
241-
error.putString("message", String.format("%s (%s)", message, ex.getMessage()));
242-
return error;
243-
}
244255
}

example/App.js

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import React, { Component } from 'react';
2+
import {
3+
StyleSheet,
4+
WebView,
5+
Platform
6+
} from 'react-native';
7+
8+
import { readdir, copyFileAssets, MainBundlePath, DocumentDirectoryPath } from 'react-native-fs';
9+
import { unzip } from 'react-native-zip-archive';
10+
11+
export default class App extends Component {
12+
constructor () {
13+
super();
14+
this.state = {
15+
uri: 'https://github.com/plrthink/react-native-zip-archive'
16+
}
17+
}
18+
19+
componentDidMount () {
20+
let sourcePath;
21+
const targetPath = DocumentDirectoryPath;
22+
23+
if (Platform.OS === 'android') {
24+
// since I can't simply get absolute path of files in assets folder,
25+
// I am copying the file from assets folder to document folder as a workaround.
26+
sourcePath = `${DocumentDirectoryPath}/static.zip`;
27+
28+
copyFileAssets('static.zip', sourcePath)
29+
.then(() => {
30+
return readdir(DocumentDirectoryPath);
31+
})
32+
.then((result) => {
33+
return unzip(sourcePath, DocumentDirectoryPath);
34+
})
35+
.then((path) => {
36+
console.log(`unzip file to ${path}`);
37+
this.setState({
38+
uri: `file://${path}/static/index.html`
39+
});
40+
})
41+
.catch((error) => {
42+
console.log(error);
43+
})
44+
} else {
45+
sourcePath = `${MainBundlePath}/static.zip`;
46+
47+
unzip(sourcePath, targetPath)
48+
.then((path) => {
49+
console.log(`unzip file to ${path}`);
50+
this.setState({
51+
uri: `${path}/static/index.html`
52+
});
53+
})
54+
.catch((error) => {
55+
console.log(error);
56+
});
57+
}
58+
}
59+
60+
render() {
61+
const { uri } = this.state
62+
63+
console.log(uri)
64+
65+
return (
66+
<WebView
67+
source={{uri: uri}}
68+
style={styles.webView}
69+
startInLoadingState={true}
70+
scalesPageToFit={true}
71+
/>
72+
);
73+
}
74+
}
75+
76+
const styles = StyleSheet.create({
77+
webView: {
78+
flex: 1,
79+
marginTop: 20,
80+
},
81+
});
621 Bytes
Binary file not shown.

example/index.android.js

Lines changed: 4 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,15 @@ import React, { Component } from 'react';
88
import {
99
AppRegistry,
1010
StyleSheet,
11-
Text,
1211
View
1312
} from 'react-native';
13+
import App from './App';
1414

1515
export default class example extends Component {
1616
render() {
1717
return (
1818
<View style={styles.container}>
19-
<Text style={styles.welcome}>
20-
Welcome to React Native!
21-
</Text>
22-
<Text style={styles.instructions}>
23-
To get started, edit index.android.js
24-
</Text>
25-
<Text style={styles.instructions}>
26-
Double tap R on your keyboard to reload,{'\n'}
27-
Shake or press menu button for dev menu
28-
</Text>
19+
<App />
2920
</View>
3021
);
3122
}
@@ -34,20 +25,8 @@ export default class example extends Component {
3425
const styles = StyleSheet.create({
3526
container: {
3627
flex: 1,
37-
justifyContent: 'center',
38-
alignItems: 'center',
39-
backgroundColor: '#F5FCFF',
40-
},
41-
welcome: {
42-
fontSize: 20,
43-
textAlign: 'center',
44-
margin: 10,
45-
},
46-
instructions: {
47-
textAlign: 'center',
48-
color: '#333333',
49-
marginBottom: 5,
50-
},
28+
alignItems: 'stretch',
29+
}
5130
});
5231

5332
AppRegistry.registerComponent('example', () => example);

0 commit comments

Comments
 (0)