Приложение React Native CouchDB / pouchDB не работает в выпуске apk - PullRequest
0 голосов
/ 16 марта 2020

Я пытаюсь сделать простой проект словаря, я использую CouchDB для удаленного сервера и pouchDB для локального.

, и я использую удаленный текстовый файл для предварительной загрузки данных в локальную базу данных.

Это мой код

import React, { Component } from 'react';
...
import { localNoteDb, nameIndex, remote_url, remoteNoteDb } from '../const'

...
let handlerSync = null

class Home extends Component {

    constructor(props) {

        super(props);
        this.state = {
            arrNote1: [],
            arrNotee: [],
            isLoading: false,
            text: '',
            count: 0,
            data1: 0,
            data2: 0,
            indicator: false,
            flagadd: false,
            notfoundFlag: false
        }
    }
    ....

    componentDidMount() {
        this.getListNoteFromDb();

    }

    componentWillUnmount() {
        this.getListNoteFromDb();
    }




    syncDb = () => {

        this.setState({ isLoading: true });


        //here is my text file to pre load the data from remote amazon s3 text file
        localNoteDb.load('https://dictionary.s3.ap-north-14321.amazonaws.com/dumpdb.txt', { proxy: remote_url }).then(() => {


            localNoteDb.replicate.from(remote_url).on('complete', function () {
                console.log("DONE>>>>>>>")
            }).on('error', function (err) {
                console.log("ERROR>>>>>" + JSON.stringify(err))
            });
            var temp = localNoteDb.replicate.from(remote_url, {
                live: true,
                retry: true
            });
            this.setState({ isLoading: false });
            return temp;

        }).catch((err) => {
            this.setState({ isLoading: false });
        });



    };

    getListNoteFromDb = () => {
        this.setState({ isLoading: true })


        fetch("http://myipaddress:5984/dictionary")
            .then(Response => Response.json())
            .then(response => {
                localNoteDb.info().then((resp) => {
                    console.log(JSON.stringify(resp))
                    //resp will contain disk_size
                    if (resp.doc_count !== response.doc_count) {
                        this.syncDb();
                    } else {
                        this.setState({ isLoading: false })
                    }
                }).catch((err) => {
                    console.log("ERROR<<<<<<" + err);
                });

            });

    }


    getListNoteFromDbText = (txt) => {

        this.setState({ text: txt, indicator: true, notfoundFlag: false })

        clearTimeout(this.timer);
        this.timer = setTimeout(function () {
            localNoteDb
                .allDocs({
                    include_docs: true,
                    attachments: true,
                    startkey: txt.toLowerCase(),
                    endkey: txt.toLowerCase() + '\ufff0'
                }).then(function (result) {
                    if (result.rows.length > 0) {
                        // handle result

                        this.setState({
                            indicator: false,
                            arrNote1: result.rows.slice(0, 10)
                        })
                        clearTimeout(this.timer);
                    } else {
                        this.setState({
                            indicator: false,
                            notfoundFlag: true
                        })
                    }


                }.bind(this))
                .catch(err => {
                    this.setState({ isLoading: false })
                    Toast.show(err.message)
                })
        }.bind(this),
            100
        );

    }

    renderItem = ({ item }) => {

        console.log("ITEMS....." + JSON.stringify(item));
        return (
            <TouchableHighlight
                underlayColor={'#98c5ba'}
                onPress={() => {
                    this.isAtCurrentScreen = false
                    this.props.addWordHistory(item.doc)
                    this.props.navigation.navigate('DetailsMeaning', {
                        idNote: item.doc,
                    })

                }}
                style={{ marginLeft: 10, marginTop: 3, marginRight: 10 }}
            >
                <Text numberOfLines={1} style={{ color: '#29282A', margin: 5, fontSize: 16, fontFamily: 'Roboto-Regular' }}>{item.doc._id}</Text>

            </TouchableHighlight>
        )
    }
    render() {
        return this.state.isLoading ? <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#f3fffc' }}><ActivityIndicator size="large" color="#ff6a00" /><Text>Fetching Data Please wait...</Text></View> : <View style={{ flex: 1, backgroundColor: '#f3fffc', zIndex: 1 }}><View style={{ marginLeft: 15, marginRight: 15, zIndex: 2, marginTop: -28 }}>
            <SearchBar
                placeholder="Type Here..."
                lightTheme={true}
                color='black'
                searchIcon={{ size: 30, color: '#3ea58d' }}
                inputStyle={{ backgroundColor: 'white' }}
                inputContainerStyle={{ backgroundColor: 'white', height: 30 }}
                containerStyle={{ backgroundColor: 'white', borderWidth: 1, borderColor: '#3ea58d', borderRadius: 5 }}
                onChangeText={(text) => this.getListNoteFromDbText(text)}
                value={this.state.text}
            />
        </View>
            {this.state.text === '' ? <Text></Text> :
                (this.state.indicator ? <View style={{ flex: 1 }}><ActivityIndicator size="large" color="#ff6a00" /></View> : <View style={{ flex: 1, flexDirection: 'column' }}><Text style={{ backgroundColor: '#98c5ba', textAlign: 'center', color: 'white', marginTop: 5, marginLeft: 15, marginRight: 15, borderRadius: 3, fontFamily: 'Roboto-Black' }}>RESULTS</Text>{this.state.notfoundFlag ? (<Text style={{ textAlign: 'center', color: 'black', marginTop: 50, fontSize: 21, fontWeight: 'bold', fontStyle: 'italic' }}>Not Found</Text>) : (<FlatList
                    style={{ backgroundColor: '#f3fffc', marginTop: 6 }}
                    data={this.state.arrNote1}
                    showsVerticalScrollIndicator={false}
                    keyExtractor={(item, index) => index.toString()}
                    renderItem={this.renderItem}
                />)}</View>)}
            <View style={{ marginTop: 1, position: 'absolute', bottom: 0 }}>
                <AdsBanner />
            </View>
        </View>

    }
}
const mapStateToProps = (state) => {
    return {
        wordHistory: state.addHistory.wordDetails
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        addWordHistory: (product) => dispatch({ type: 'ADD_WORD', payload: product })
    }


}
export default connect(mapStateToProps, mapDispatchToProps)(Home);

Код Base64, я поместил ссылку в индекс.

import {decode, encode} from 'base-64'

if (!global.btoa) {
    global.btoa = encode;
}

if (!global.atob) {
    global.atob = decode;
}

process.browser = true

Он отлично работает в режиме отладки, но не в режиме выпуска.

У меня была та же проблема, что и у

React Native atob () / btoa () не работает без удаленного JS отладка

Все отлично работает в режиме отладки, установив base64 код, но когда я делаю ./gradlew assembleRelease и проверяю apk, данные не могут быть загружены.

В выпуске apk также он показывает ту же проблему, что и выше.

Это связано с проблемой base64 или любая другая проблема? Пожалуйста помоги. Спасибо.

...