Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

App crash on file pick in android #286

Closed
maxbhoria opened this issue Jun 8, 2020 · 99 comments
Closed

App crash on file pick in android #286

maxbhoria opened this issue Jun 8, 2020 · 99 comments
Labels
android Issue applies to Android platform needs investigation new issue An issue that hasn't yet been seen from the maintainer

Comments

@maxbhoria
Copy link

Hi i am not able to pick file app get crashed when i select any file.

I an using android device.

Issue printed in console

E/AndroidRuntime( 1459): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
E/AndroidRuntime( 1459): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:92)
E/AndroidRuntime( 1459): at java.lang.Thread.run(Thread.java:919)

@maxbhoria maxbhoria added the new issue An issue that hasn't yet been seen from the maintainer label Jun 8, 2020
@maxbhoria maxbhoria changed the title File not picking on my android device App crash on file pick in android Jun 8, 2020
@miguelpruivo
Copy link
Owner

Hi, how are you picking the file?

@maxbhoria
Copy link
Author

Hi, how are you picking the file?

I am using this code

void pickFile() async {
setState(() => _loadingPath = true);
try {
_path = null;
_path = await FilePicker.getFilePath(
type: _pickingType, allowedExtensions: (_extension?.isNotEmpty ?? false) ? _extension?.replaceAll(' ', '')?.split(',') : null);
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (!mounted) return;
setState(() {
_loadingPath = false;
_fileName = _path != null ? _path.split('/').last : _paths != null ? _paths.keys.toString() : '...';
});
}

@miguelpruivo
Copy link
Owner

Please, don’t use that. That’s an example code that’s made to fit a lot of use cases with a few lines and shouldn’t be used at on your project.

Check the plugin’s Wiki that has a lot of well documented examples for each use case and let me know if it worked for you.

Thanks!

@maxbhoria
Copy link
Author

maxbhoria commented Jun 8, 2020

Please, don’t use that. That’s an example code that’s made to fit a lot of use cases with a few lines and shouldn’t be used at on your project.

Check the plugin’s Wiki that has a lot of well documented examples for each use case and let me know if it worked for you.

Thanks!

Now i used this code but app still crashing

File extraFile = await FilePicker.getFile(type: FileType.any);
setState(() {
fileName = basename(extraFile.path);
});

Error Logs
E/AndroidRuntime(20193): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
E/AndroidRuntime(20193): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:92)
E/AndroidRuntime(20193): at java.lang.Thread.run(Thread.java:919)
E/FilePickerUtils(20193): Document URI
E/FilePickerUtils(20193): External Document URI
E/FilePickerUtils(20193): Primary External Document URI
I/FilePickerDelegate(20193): Absolute file path:/storage/emulated/0/Download/dbs-postgraduate-fees-2015-16.pdf

@maxbhoria maxbhoria reopened this Jun 8, 2020
@miguelpruivo
Copy link
Owner

@maxbhoria when you run the example app, does that happen?

@maxbhoria
Copy link
Author

@maxbhoria when you run the example app, does that happen?
No this is not happened when i download code from github.

@miguelpruivo
Copy link
Owner

Hum, there must be something in your project that's resulting in type being null. Which file_picker version are you on? By looking at your stack trace, it's invoking type as null in a place where it can't be null.

Also, run a full flutter clean and build again.

@maxbhoria
Copy link
Author

maxbhoria commented Jun 8, 2020

Hum, there must be something in your project that's resulting in type being null. Which file_picker version are you on? By looking at your stack trace, it's invoking type as null in a place where it can't be null.

Also, run a full flutter clean and build again.

Plugin version is file_picker: ^1.10.0
tried many time with flutter clean

Can you tell me how to directly use github plugin directly in my app?

@miguelpruivo
Copy link
Owner

If you can't reproduce it with the example app, then likely there must be something related to some conflict on your project.

There's no need to use the github project directly on your project as it won't make any difference or whatsoever, but may help you get rid of cached issues. You can give it a try. Just use it like this:

file_picker:
  git: https://github.com/miguelpruivo/flutter_file_picker.git

@maxbhoria
Copy link
Author

If you can't reproduce it with the example app, then likely there must be something related to some conflict on your project.

There's no need to use the github project directly on your project as it won't make any difference or whatsoever, but may help you get rid of cached issues. You can give it a try. Just use it like this:

file_picker:
  git: https://github.com/miguelpruivo/flutter_file_picker.git

ok thanks, let me try this!

@maxbhoria
Copy link
Author

maxbhoria commented Jun 8, 2020

file_picker:
git: https://github.com/miguelpruivo/flutter_file_picker.git

it also did not worked error is same

@miguelpruivo
Copy link
Owner

Yes, like I told you, pubdev has the same version. I really would like to help you, but I quite don't get what might be triggering it. Maybe post your code block that's asking for the picker.

@maxbhoria
Copy link
Author

Yes, like I told you, pubdev has the same version. I really would like to help you, but I quite don't get what might be triggering it. Maybe post your code block that's asking for the picker.

however it does not require any specific setting for android

@maxbhoria
Copy link
Author

Yes, like I told you, pubdev has the same version. I really would like to help you, but I quite don't get what might be triggering it. Maybe post your code block that's asking for the picker.

This is complete log have a look in that please

D/SurfaceView(31692): windowStopped(true) false io.flutter.embedding.android.FlutterSurfaceView{9be883b V.E...... ........ 0,0-1080,2301} of ViewRootImpl@98d2c27[MainActivity]
D/FlutterView(31692): Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@4d2e4be
D/SurfaceView(31692): onWindowVisibilityChanged(4) false io.flutter.embedding.android.FlutterSurfaceView{9be883b V.E...... .......D 0,0-1080,2301} of ViewRootImpl@98d2c27[MainActivity]
D/ViewRootImpl@98d2c27MainActivity: Relayout returned: old=(0,0,1080,2340) new=(0,0,1080,2340) req=(1080,2340)4 dur=12 res=0x1 s={false 0} ch=false
I/FilePickerDelegate(31692): [SingleFilePick] File URI:content://com.android.externalstorage.documents/document/primary%3ADownload%2F4w2E4661.jpg
E/FilePickerUtils(31692): Getting for API 19 or abovecontent://com.android.externalstorage.documents/document/primary%3ADownload%2F4w2E4661.jpg
D/ViewRootImpl@98d2c27MainActivity: stopped(false) old=true
D/SurfaceView(31692): windowStopped(false) false io.flutter.embedding.android.FlutterSurfaceView{9be883b V.E...... .......D 0,0-1080,2301} of ViewRootImpl@98d2c27[MainActivity]
E/AndroidRuntime(31692): FATAL EXCEPTION: Thread-6
E/AndroidRuntime(31692): Process: com.babymotherprescription, PID: 31692
E/AndroidRuntime(31692): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
E/AndroidRuntime(31692): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:92)
E/AndroidRuntime(31692): at java.lang.Thread.run(Thread.java:919)
D/ViewRootImpl@98d2c27MainActivity: stopped(false) old=false
E/FilePickerUtils(31692): Document URI
E/FilePickerUtils(31692): External Document URI
E/FilePickerUtils(31692): Primary External Document URI
I/FilePickerDelegate(31692): Absolute file path:/storage/emulated/0/Download/4w2E4661.jpg
D/SurfaceView(31692): onWindowVisibilityChanged(0) true io.flutter.embedding.android.FlutterSurfaceView{9be883b V.E...... .......D 0,0-1080,2301} of ViewRootImpl@98d2c27[MainActivity]
D/ViewRootImpl@98d2c27MainActivity: Relayout returned: old=(0,0,1080,2340) new=(0,0,1080,2340) req=(1080,2340)0 dur=14 res=0x7 s={true 496188772352} ch=true
D/OpenGLRenderer(31692): createReliableSurface : 0x740b61bd00, 0x738727d000
I/mali_winsys(31692): new_window_surface() [1080x2340] return: 0x3000
D/SurfaceView(31692): surfaceCreated 1 #8 io.flutter.embedding.android.FlutterSurfaceView{9be883b V.E...... .......D 0,0-1080,2301}
D/SurfaceView(31692): surfaceChanged (1080,2301) 1 #8 io.flutter.embedding.android.FlutterSurfaceView{9be883b V.E...... .......D 0,0-1080,2301}
I/Process (31692): Sending signal. PID: 31692 SIG: 9

@maxbhoria
Copy link
Author

i tried with another new project but the output is same. Have you find anything or have you tried by creating new project to check?

@maxbhoria
Copy link
Author

Do you remember any other settings that you did in your example because i don't how your example running perfectly

@maxbhoria
Copy link
Author

maxbhoria commented Jun 8, 2020

is this the problem because of i am using kotlin and your plugin is in java?? Because i copy your android folder from the example and i paste it into my sample it worked for me

@miguelpruivo
Copy link
Owner

It shouldn't have any issue with kotlin projects. But try recreating your project from scratch or run flutter create . on your project so it can add missing files and run it again.

@maxbhoria
Copy link
Author

Hello
I commented this code in plugin FilePickerDeligate.java, will it create any further issue in my application?

// if (type.equals("dir") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// uri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri));
// }

@miguelpruivo
Copy link
Owner

If you’re not planning to pick directories then not. I forgot to ask, what’s the minimum Android sdk of your app?

@maxbhoria
Copy link
Author

If you’re not planning to pick directories then not. I forgot to ask, what’s the minimum Android sdk of your app?

yes of course i don't have plan to pick dir as of now but Please make a fix for this problem and my mini sdk is 21.

Thanks for your support

@miguelpruivo
Copy link
Owner

@maxbhoria I can’t make a fix if I don’t get what’s triggering your issue but I’ll give it a look, could you please tell me details of your app’s build gradle and which version your android device is on?

@maxbhoria
Copy link
Author

You can check by creating a new project what wrong is triggered beacause i tried by creating new project also.

I am using Andorid 10 and this is app level gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
compileSdkVersion 29

sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
}

lintOptions {
    disable 'InvalidPackage'
}

defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.babymotherprescription"
    minSdkVersion 21
    targetSdkVersion 29
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        // TODO: Add your own signing config for the release build.
        // Signing with the debug keys for now, so `flutter run --release` works.
        signingConfig signingConfigs.debug
    }
}

}

flutter {
source '../..'
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

@nicolas-costa
Copy link

@maxbhoria if you want a quick workaround, use file_picker: 1.7.0.
I was facing the same issue here, strangely enough, the code was working on Friday 5.
The older version "solved" it.

@miguelpruivo
Copy link
Owner

@nicolas-costa did you update it since Friday? The last update only introduced directory picks but for some reason this issue results in file type (apparently) being null where it can’t be, still trying to understand what might be resulting in it but no luck so far.

@nicolas-costa
Copy link

@miguelpruivo I didn't intentionally updated it. What I can tell you is that I installed it last week to make some tests and see if it would fit my needs. I followed the docs, where, as you know, it instructs to add "file_picker: ^1.7.1". It was working perfectly.

Then it stopped working somehow. I messed around trying to figure it out, without luck. Then stumbled on this version bump (1.10.0) on my pubspec file, found this issue and had the idea to rollback to 1.7. Boom, working again.

So I guess the package manager updated it for me due to the: ^.

@nikitaIndianic
Copy link

Screenshot_1592992744
see when i tried to pick image from that particular folder i am getting crash

@miguelpruivo
Copy link
Owner

@nikitaIndianic thanks, I'm looking into it. Does that happen only with that folder?

@nikitaIndianic
Copy link

i tried with nexus 5x emulator in this device i am getting crash while selection image from download folder too.

@miguelpruivo
Copy link
Owner

@nikitaIndianic just tried creating a new 5x emulator with the settings you gave me and it works flawlessly. There must be something else triggering the issue.

If you look into the source code, you see that the type can't be null where it is saying it is, as I have a type null check just a few lines before that. Oddly, in your activity result, the type becomes null magically.

Does that happen in a brand new Flutter project? Would you mind to try please?

@nikitaIndianic
Copy link

yes i have tried in new project but getting same issue.
yes i am too confused because before that it's working fine.

@miguelpruivo
Copy link
Owner

@nikitaIndianic post your flutter doctor -v here please.

@nikitaIndianic
Copy link

[✓] Flutter (Channel stable, v1.12.13+hotfix.9, on Mac OS X 10.15.3 19D76, locale en-IN)
• Flutter version 1.12.13+hotfix.9 at /Users/indianic/flutterSDk/flutter
• Framework revision f139b11009 (3 months ago), 2020-03-30 13:57:30 -0700
• Engine revision af51afceb8
• Dart version 2.7.2

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at /Users/indianic/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.3.1, Build version 11C504
• CocoaPods version 1.9.2

[✓] Android Studio (version 3.6)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 45.1.1
• Dart plugin version 192.8052
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)

[✓] Connected device (1 available)
• Android SDK built for x86 64 • emulator-5556 • android-x64 • Android 10 (API 29) (emulator)

• No issues found!

@miguelpruivo
Copy link
Owner

@nikitaIndianic hum, you are in an old stable that's more than 6 months old, despite having a few earlier hotfixes (I'm currently on the latest 1.17). Would you mind trying flutter upgrade and try afterwards? Might be related.

@nikitaIndianic
Copy link

i used this version bcs in latest stable version giving issue while we long press on edittext it is not giving paste option.
still let me try with latest version

@miguelpruivo
Copy link
Owner

@nikitaIndianic that's weird. Copy/paste is working properly for me. Let me know if it made any difference.

@nikitaIndianic
Copy link

yes in latest version it's working
[✓] Flutter (Channel stable, v1.17.3, on Mac OS X 10.15.3 19D76, locale en-IN)
• Flutter version 1.17.3 at /Users/indianic/flutterSDk/flutter
• Framework revision b041144f83 (3 weeks ago), 2020-06-04 09:26:11 -0700
• Engine revision ee76268252
• Dart version 2.8.4

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at /Users/indianic/Library/Android/sdk
• Platform android-29, build-tools 29.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.3.1, Build version 11C504
• CocoaPods version 1.9.2

[✓] Android Studio (version 3.6)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 45.1.1
• Dart plugin version 192.8052
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)

[✓] Connected device (1 available)
• Android SDK built for x86 64 • emulator-5556 • android-x64 • Android 10 (API 29) (emulator)

• No issues found!

@nikitaIndianic
Copy link

but i am facing issue with copy/paste will you please verify once is it option working on latest stable version

@miguelpruivo
Copy link
Owner

Ok, so basically this is an issue with Flutter on older versions, surprisingly. @maxbhoria would you mind upgrading Flutter to latest stable as well and see if its working for you? Thanks!

@maxbhoria
Copy link
Author

Ok, so basically this is an issue with Flutter on older versions, surprisingly. @maxbhoria would you mind upgrading Flutter to latest stable as well and see if its working for you? Thanks!

@miguelpruivo Sure, I will try this later and update here.

Thanks

@i-tick
Copy link

i-tick commented Jun 24, 2020

Im also facing the same issue
app crashes after picking a file

@maxbhoria
Copy link
Author

but i am facing issue with copy/paste will you please verify once is it option working on latest stable version

read this and try

@miguelpruivo
Copy link
Owner

To anyone experiencing this, please make sure you update to latest Flutter stable (currently 1.17).

@vijayFxbytes
Copy link

I am too facing the same issue
app crashes after picking a file. Please help me.

@skiryuk
Copy link

skiryuk commented Jun 25, 2020

I am too facing the same issue
app crashes after picking a file. Please help me.

Hi, try upgrade your flutter version

@vijayFxbytes
Copy link

Thx. It is working.

@miguelpruivo
Copy link
Owner

Closing as we’ve finally found the solution. To anyone reading/experiencing this:

Please update to latest Flutter stable version and it should be fixed.

Thanks!

@maxbhoria
Copy link
Author

Closing as we’ve finally found the solution. To anyone reading/experiencing this:

Please update to latest Flutter stable version and it should be fixed.

Thanks!

i would like to thank to @miguelpruivo and @nikitaIndianic who finally find the reason behind this problem.

Thanks

@miguelpruivo
Copy link
Owner

@maxbhoria thanks for reporting, I'll refer this on the Wiki troubleshooting section as well.

@MuGiMac
Copy link

MuGiMac commented Jul 6, 2020

Same here bro,..

File image;
void selectimage() async {
image=await FilePicker.getFile();

setState(() {
  image=image;
  imagepath=basename(image.path);
  uploadimagefile(image.readAsBytesSync(),imagepath);
});

}

it just keep exits,................................

V/MusicPlayerPlugin(16068): Activity Save Instance State
I/FilePickerDelegate(16068): [SingleFilePick] File URI:content://com.android.externalstorage.documents/document/primary%3AIMG_20171213_095703670_HDR-01.jpeg
E/FilePickerUtils(16068): Getting for API 19 or abovecontent://com.android.externalstorage.documents/document/primary%3AIMG_20171213_095703670_HDR-01.jpeg
E/AndroidRuntime(16068): FATAL EXCEPTION: Thread-7
E/AndroidRuntime(16068): Process: com.example.ebplayer, PID: 16068
E/AndroidRuntime(16068): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
E/AndroidRuntime(16068): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:106)
E/AndroidRuntime(16068): at java.lang.Thread.run(Thread.java:764)
V/MusicPlayerPlugin(16068): Activity Started
V/MusicPlayerPlugin(16068): Activity Resumed
E/FilePickerUtils(16068): Document URI
E/FilePickerUtils(16068): External Document URI
E/FilePickerUtils(16068): Primary External Document URI
I/FilePickerDelegate(16068): Absolute file path:/storage/emulated/0/IMG_20171213_095703670_HDR-01.jpeg
I/Process (16068): Sending signal. PID: 16068 SIG: 9
Lost connection to device.

@miguelpruivo
Copy link
Owner

@DarK-C0deR Please update to latest Flutter stable version (1.17.x) and it should be fixed.

@MuGiMac
Copy link

MuGiMac commented Jul 7, 2020

Tnq u Bro,...

@charismatest
Copy link

I am experiencing this issue on Android 8 (Galaxy A5) and 14 (emulator), getting this error after selecting a file:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference

@BonDizard
Copy link

BonDizard commented Mar 16, 2024

Please help me even for me crash is happening after picking image I'm a beginner so I'm following this course but the guy who did the course did not have crash but I'm getting now idk y.

Flutter 3.19.3 • channel stable

I/flutter ( 7623): granted
D/FilePickerDelegate( 7623): Selected type image/*
D/BLASTBufferQueue( 7623): SurfaceView[com.example.reddit_clone/com.example.reddit_clone.MainActivity]#1 destructor()
D/BufferQueueConsumer( 7623): SurfaceView[com.example.reddit_clone/com.example.reddit_clone.MainActivity]#1(BLAST Consumer)1 disconnect
D/BLASTBufferQueue( 7623): VRI[MainActivity]#0 destructor()
D/BufferQueueConsumer( 7623): VRI[MainActivity]#0(BLAST Consumer)0 disconnect
D/CompatibilityChangeReporter( 7623): Compat change id reported: 78294732; UID 10480; state: ENABLED
D/BufferQueueConsumer( 7623): connect: controlledByApp=false
E/OpenGLRenderer( 7623): Unable to match the desired swap behavior.
D/BufferQueueConsumer( 7623): connect: controlledByApp=false
D/BLASTBufferQueue( 7623): VRI[MainActivity]#2 acquireNextBufferLocked size=1080x2400 mFrameNumber=1 applyTransaction=true mTimestamp=131279244526977(auto) mPendingTransactions.size=0 graphicBufferId=32740535697414 transform=0
D/BLASTBufferQueue( 7623): SurfaceView[com.example.reddit_clone/com.example.reddit_clone.MainActivity]#3 acquireNextBufferLocked size=1080x2349 mFrameNumber=1 applyTransaction=true mTimestamp=131279249779285(auto) mPendingTransactions.size=0 graphicBufferId=32740535697415 transform=0
E/BitmapFactory( 7623): Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Android/media/com.whatsapp/WhatsApp/Media/WhatsApp Images/IMG-20240316-WA0000.jpg: open failed: EACCES (Permission denied)
E/AndroidRuntime( 7623): FATAL EXCEPTION: Thread-6
E/AndroidRuntime( 7623): Process: com.example.reddit_clone, PID: 7623
E/AndroidRuntime( 7623): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
E/AndroidRuntime( 7623): at com.mr.flutter.plugin.filepicker.FileUtils.compressImage(FileUtils.java:106)
E/AndroidRuntime( 7623): at com.mr.flutter.plugin.filepicker.FilePickerDelegate$2.run(FilePickerDelegate.java:104)
E/AndroidRuntime( 7623): at java.lang.Thread.run(Thread.java:1012)
I/Process ( 7623): Sending signal. PID: 7623 SIG: 9
Lost connection to device.


import 'dart:io';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter/material.dart';
import 'package:reddit_clone/core/common/error_text.dart';
import 'package:reddit_clone/core/common/loader.dart';
import 'package:reddit_clone/core/constants/constants.dart';
import 'package:reddit_clone/core/utils.dart';
import 'package:reddit_clone/features/community/controller/community_controller.dart';
import 'package:reddit_clone/models/community_model.dart';
import 'package:reddit_clone/theme/pallet.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';

class EditCommunityScreen extends ConsumerStatefulWidget {
  final String name;
  const EditCommunityScreen({
    super.key,
    required this.name,
  });

  @override
  ConsumerState<EditCommunityScreen> createState() =>
      _EditCommunityScreenState();
}

class _EditCommunityScreenState extends ConsumerState<EditCommunityScreen> {
  File? bannerFile;
  File? profileFile;

  void test() async {
    final plugin = DeviceInfoPlugin();
    final android = await plugin.androidInfo;

    final storageStatus = android.version.sdkInt < 33
        ? await Permission.storage.request()
        : PermissionStatus.granted;

    if (storageStatus == PermissionStatus.granted) {
      print("granted");
    }
    if (storageStatus == PermissionStatus.denied) {
      print("denied");
    }
    if (storageStatus == PermissionStatus.permanentlyDenied) {
      openAppSettings();
    }
  }

  @override
  void initState() {
    super.initState();
    test();
  }

  void save(Community community) {
    ref.read(communityControllerProvider.notifier).editCommunity(
          profileFile: profileFile,
          bannerFile: bannerFile,
          context: context,
          community: community,
        );
  }

  void selectBannerImage() async {
    final res = await pickImage();
    if (res != null) {
      setState(() {
        final filePath = res.files.first.path;
        if (filePath != null) {
          bannerFile = File(filePath);
        } else {
          // Fallback to default image if file path is null
          bannerFile = File('assets/images/google.png');
          print('File path is null');
        }
      });
    }
  }

  void selectProfileImage() async {
    final res = await pickImage();
    if (res != null) {
      setState(() {
        final filePath = res.files.first.path;
        if (filePath != null) {
          profileFile = File(filePath);
        } else {
          // Fallback to default image if file path is null
          profileFile = File('assets/images/google.png');
          print('File path is null');
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ref.watch(getCommunityNameByNameProvider(widget.name)).when(
          data: (community) => Scaffold(
            backgroundColor: Pallete.darkModeAppTheme.backgroundColor,
            appBar: AppBar(
              title: const Text("Edit Community"),
              actions: [
                TextButton(
                  onPressed: () {
                    save(community);
                  },
                  child: const Text(
                    'Save',
                  ),
                ),
              ],
            ),
            body: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SizedBox(
                height: 300,
                child: Column(
                  children: [
                    Stack(
                      children: [
                        GestureDetector(
                          onTap: () {
                            selectBannerImage();
                          },
                          child: DottedBorder(
                            borderType: BorderType.RRect,
                            radius: const Radius.circular(10),
                            dashPattern: const [10, 4],
                            strokeCap: StrokeCap.round,
                            color: Pallete
                                .darkModeAppTheme.textTheme.bodySmall!.color!,
                            child: Container(
                              width: double.infinity,
                              height: 150,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: bannerFile != null
                                  ? Image.file(bannerFile!)
                                  : community.banner.isEmpty ||
                                          community.banner ==
                                              Constants.bannerDefault
                                      ? const Center(
                                          child: Icon(
                                            Icons.camera_alt_outlined,
                                            size: 40,
                                          ),
                                        )
                                      : Image.network(community.banner),
                            ),
                          ),
                        ),
                        Positioned(
                          bottom: 20,
                          left: 20,
                          child: GestureDetector(
                            onTap: () {
                              selectProfileImage();
                            },
                            child: profileFile != null
                                ? CircleAvatar(
                                    backgroundImage: FileImage(profileFile!),
                                    radius: 32,
                                  )
                                : CircleAvatar(
                                    backgroundImage:
                                        NetworkImage(community.avatar),
                                    radius: 32,
                                  ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          error: (error, stackTrace) => ErrorText(
            error: error.toString(),
          ),
          loading: () => const Loader(),
        );
  }
}

//the below is the method for picking image


Future<FilePickerResult?> pickImage() async {
  final image = await FilePicker.platform.pickFiles(type: FileType.image);

  return image;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
android Issue applies to Android platform needs investigation new issue An issue that hasn't yet been seen from the maintainer
Projects
None yet
Development

No branches or pull requests