development

FileProvider 충돌-null 문자열에서 XmlResourceParser를 호출하려고 시도합니다.

big-blog 2020. 7. 1. 07:33
반응형

FileProvider 충돌-null 문자열에서 XmlResourceParser를 호출하려고 시도합니다.


이것은 내 매니페스트의 일부입니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.asd"
    android:versionCode="118"
    android:versionName="118" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />


    <application
        android:name="com.example.asd.AsdApplication"
        android:allowBackup="true"
        android:allowTaskReparenting="true"
        android:theme="@style/AsdTheme" >
        ...

        <provider
            android:name="com.example.asd.database.hq.ContentProviderDB"
            android:authorities="ourContentProviderAuthorities" >
        </provider>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.asd.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>

       ...
    </application>

</manifest>

이것은 raw / xml / filepaths.xml의 파일 경로 파일입니다.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="media"/>
</paths>

인터넷에서 비디오를 다운로드하여 다음과 같이 내부 저장소에 저장합니다.

public static boolean saveInputStreamToInternalStorageFile(Context context, String filename, byte[] dataToWrite, Context ctx) {
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(context.getFilesDir() + File.separator + filename);

        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(dataToWrite);
        oos.close();
        return true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

나는 그렇게 사용하려고합니다 :

private void playVideoFromDeviceWithWorkaround(String fileName) {

    File newFile = new File(getFilesDir(), fileName);
    Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile);

    try {
        vvVideoFullscreen.setVideoURI(contentUri);
        showMediaControls = true;
        playVideo();
    } catch (Exception e) {
        playVideoFromNetwork();
    }

}

이 라인에서 :

Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile); 

다음과 같은 오류가 발생합니다.

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:560)
at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:534)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:376)

문제는 매니페스트 에서이 줄을 가지고 있다는 것입니다.

android:authorities="com.example.asd.fileprovider"

그리고 getUriForFile을 호출 할 때 나는 통과했다 :

Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile); 

그래서에서 "com.example.asd"바뀌었고 "com.example.asd.fileprovider"효과가있었습니다.


당신은 동일한 장치 (생각의 여러 변종 실행할 수있는의 추가 혜택과 함께 패키지 이름을 하드 코딩하지 않고이 작업을 수행 할 수 releasedebugapplicationIdSuffix볼, 이러한 문제를 )

에 기초 FileProvider.java:560

final ProviderInfo info = context.getPackageManager()
        .resolveContentProvider(authority, PackageManager.GET_META_DATA);
final XmlResourceParser in = info.loadXmlMetaData( //560
        context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);

당신이 잘못 사용하고 있었고 ( )를 authority찾지 못했습니다 .ContentProviderinfo == null

Change your manifest to (${applicationId} will be replaced by Manifest Merger)

android:authorities="${applicationId}.share"

and

Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".share", result);

The .share suffix is optional, in case you have a real ContentProvider which is better to have the package name as the authority.


In my case, I got the error because the

BuildConfig.APPLICATION_ID

was being imported from

import android.support.v4.BuildConfig;

So the string it returned was "android.support.v4" instead of my project package name. Check out the import file is from your import project.Buildconfig and not another. Example:

import com.example.yourProjectName.BuildConfig;

Finally, in <provider> tag in Manifest I have android:authorities="${applicationId}" to always get my project package name as the authority

<manifest>
   ..
   ..
   <application>
    ..
    ..
       <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/ruta_fileprovider" />
        </provider>

    </application>

</manifest>

First, be sure that you provider android:authorities does not conflict with your other providers. Besides that you may choose any name for the last part of its name: "provider", "fileprovider" etc., but app crashes when there are more than one android:authorities listed, while documentation states that it allows multiple values listed.

file:// scheme is now not allowed to be attached with Intent on targetSdkVersion >= 24 (Android N 7.0), only content:// is always passed for all devices (Android 5, 6 and 7). But we encountered that Xiaomi breaks this Google convention and sends file://, hence data.getData().getAuthority() gives empty string.

final String uriScheme = currentUri.getScheme();
if ("content".equals(uriScheme)) {
    // getting full file path (works with some providers, i.e. Gallery)
    path = FileUtils.getPath(getContext(), currentUri);
    if (path != null) {
         currentFile = new File(path);
    }
} else if ("file".equals(uriScheme)) {
    // in a rare case we received file:// in currentUri, we need to:
    // 1. create new File variable from currentUri that looks like "file:///storage/emulated/0/download/50044382b.jpg"
    // 2. generate a proper content:// Uri for it
    currentFile = new File(currentUri.getPath());
    String authority = data.getData().getAuthority();
    if (authority != null && !authority.isEmpty()) {
        currentUri = FileProvider.getUriForFile(getActivity(), authority, currentFile);
    }
} else {
    // throw exception
}

Also, the bug when FileProvider.getUriForFile() resulted in crash java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example/files/attachments/image.jpg was fixed in Android Support Library v24.2.0. The problem was that FileProvider.java did not see external-path folders.


If you're building your AUTHORITY at runtime using BuildConfig make sure you use the full class name including your package name.

Bad:

final String AUTHORITY = BuildConfig.APPLICATION_ID + ".provider";

Good:

final String AUTHORITY = com.mycompany.myapp.BuildConfig.APPLICATION_ID + ".provider";


Following worked for me.

mUri = FileProvider.getUriForFile(this,
                    BuildConfig.APPLICATION_ID + ".provider",
                    fileObject);

Here is what i did to fix the issue. I gave fully qualified name in android:name. It works in android 6,7,8

    <provider android:authorities="${applicationId}.opener.provider" 
        android:exported="false" android:grantUriPermissions="true" 
        android:name="io.github.pwlin.cordova.plugins.fileopener2.FileProvider">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
    </provider>

You should try it:

  Context context = PostAdapter.this.activity;
                    StringBuilder stringBuilder2 = new StringBuilder();
                    stringBuilder2.append(PostAdapter.this.activity.getPackageName());
                    stringBuilder2.append(".provider");
                    Uri uri;
                    uri = FileProvider.getUriForFile(context,stringBuilder2.toString(), newFile);

참고URL : https://stackoverflow.com/questions/30896130/fileprovider-crash-npe-attempting-to-invoke-xmlresourceparser-on-a-null-string

반응형