У меня есть приложение React Native Expo, но оно продолжает выдавать эту ошибку:
Attempt to invoke virtual method 'byte[] java.lang.String.getBytes()' on a null object reference
at node_modules\react-native\Libraries\BatchedBridge\NativeModules.js:103:50 in promiseMethodWrapper
at node_modules\@unimodules\react-native-adapter\build\NativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name
at node_modules\expo-file-system\build\FileSystem.js:50:17 in writeAsStringAsync
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:293:29 in invoke
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:154:27 in invoke
at node_modules\regenerator-runtime\runtime.js:189:16 in PromiseImpl$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:45:6 in tryCallTwo
at node_modules\react-native\node_modules\promise\setimmediate\core.js:200:22 in doResolve
at node_modules\react-native\node_modules\promise\setimmediate\core.js:66:11 in Promise
at node_modules\regenerator-runtime\runtime.js:188:15 in callInvokeWithMethodAndArg
at node_modules\regenerator-runtime\runtime.js:211:38 in enqueue
at node_modules\regenerator-runtime\runtime.js:238:8 in exports.async
at node_modules\expo-file-system\build\FileSystem.js:46:7 in writeAsStringAsync
at screens\Export.js:74:12 in fetch.then.then$argument_0
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:293:29 in invoke
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:154:27 in invoke
at node_modules\regenerator-runtime\runtime.js:189:16 in PromiseImpl$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:45:6 in tryCallTwo
at node_modules\react-native\node_modules\promise\setimmediate\core.js:200:22 in doResolve
at node_modules\react-native\node_modules\promise\setimmediate\core.js:66:11 in Promise
at node_modules\regenerator-runtime\runtime.js:188:15 in callInvokeWithMethodAndArg
at node_modules\regenerator-runtime\runtime.js:211:38 in enqueue
at node_modules\regenerator-runtime\runtime.js:238:8 in exports.async
at screens\Export.js:65:14 in exportReport
at node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
at node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14 in _callImmediatesPass
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 in callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6 in __callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue
at [native code]:null in flushedQueue
at [native code]:null in invokeCallbackAndReturnFlushedQueue
Это код, который создает эту ошибку. Кажется, это ошибка Java, хотя я использую реагирующую нативную выставку.
const exportReport = async () => {
if (validate()) {
setLoading(true);
let token = await SecureStore.getItemAsync("token");
return await fetch("https://notrealapi.herokuapp.com/api/export", {
method: "POST",
headers: {
"content-type": "application/json",
Authorization: `JWT ${JSON.parse(token)}`,
},
body: JSON.stringify({ note: note, mission: value }),
})
.then((res) => res.json())
.then(async (json) => {
if (json.hasOwnProperty("msg")) {
Alert.alert(json.msg);
} else {
setLoading(false);
console.log(json);
setReportUrl("data:application/pdf;base64," + json.pdf);
console.log(reportUrl);
const base64Code = reportUrl.split(
"data:application/pdf;base64,"
)[1];
const filename = FileSystem.documentDirectory + "report.pdf";
console.log(base64Code);
await FileSystem.writeAsStringAsync(filename, base64Code, {
encoding: FileSystem.EncodingType.Base64,
});
const _mediaResult = await MediaLibrary.saveToLibraryAsync(
filename
);
await Sharing.shareAsync(filename);
}
})
.catch((error) => console.error(error));
}
};
Я получаю строку из серверной части, затем делаю из этой строки URL-адрес данных, а затем сохраняю этот URL-адрес данных в формате pdf на телефоне пользователя. Это работает после нескольких попыток.
Кроме того, вот как серверная часть выдает строку (с использованием Django):
pdfStr = pdf.output(dest="S").encode("latin-1")
encodedPdfStr = base64.b64encode(pdfStr)
return Response({"pdf": encodedPdfStr})
Мы будем признательны за любую помощь.
Спасибо.
filename
илиbase64code
null
?Я думаю, что проблема возникла раньше, потому что эта ошибка возникла до того, как что-либо было распечатано.
Может быть, он ничего не распечатал, потому что именно так он интерпретировал
null
при печати? Кроме того, вы можете использовать отладчик, чтобы найти ошибку.После дальнейшей проверки он распечатал json. Поэтому я думаю, что проблема в:
setReportUrl("data:application/pdf;base64," + json.pdf); console.log(reportUrl);
В ошибке упоминается
writeAsStringAsync
, так что это может быть проблемой.Но он печатает
reportUrl
как undefinedОзначает ли это, что строка может быть слишком длинной?
undefined
иnull
в основном означают, что чего-то не существует.Но я установил состояние использования
reportUrl
, поэтому, возможно, ошибка может заключаться в том, что он не может хранить слишком длинную строку, верно?