英文:
Android URI error java.io.FileNotFoundException: No content provider: http://
问题
Bundle fileParams = getIntent().getExtras();
filePosition = fileParams.getInt("index");
allFiles = fileParams.getStringArrayList("arrayList");
photoOpenerAdapter = new PhotoOpenerAdapter(allFiles, cntxt);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(photoOpenerAdapter);
viewPager.setCurrentItem(filePosition);
viewPager.setOffscreenPageLimit(allFiles.size());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
viewPager.post(new Runnable() {
@Override
public void run() {
if (!loadedInitial) {
loadedInitial = true;
String filePath = allFiles.get(position);
String fileType = functions.getmInstance(cntxt).checkFileType(filePath);
if (fileType.equals("video"))
startVideoPlayer(position);
}
}
});
}
@Override
public void onPageSelected(int position) {
pauseVideoPlayer();
String filePath = allFiles.get(position);
String fileType = functions.getmInstance(cntxt).checkFileType(filePath);
if (fileType.equals("video")) {
startVideoPlayer(position);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
private void pauseVideoPlayer() {
if (!(videoView == null)) {
videoView.pause();
}
}
public static void startVideoPlayer(int position) {
View videoLayout = viewPager.getChildAt(position);
videoView = (VideoView) videoLayout.findViewById(R.id.videoPlayer);
if (!(videoView == null)) {
videoView.requestFocus();
videoView.start();
}
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, final int position) {
layoutInflater = LayoutInflater.from(context);
String imageUrl = postFilesLists.get(position);
String fileType = functions.getmInstance(context).checkFileType(imageUrl.toLowerCase());
if (fileType.equals("video")) {
view = layoutInflater.inflate(R.layout.video_player, container, false);
VideoView videoView = (VideoView) view.findViewById(R.id.videoPlayer);
Uri uri = Uri.parse(imageUrl);
videoView.setVideoURI(uri);
} else {
view = layoutInflater.inflate(R.layout.photo_opener, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
imageLoader.displayImage(imageUrl, imageView);
}
container.addView(view);
return view;
}
This code handles the creation and display of images and videos using a ViewPager. It defines methods to pause and play video playback and utilizes an adapter to create the view items. The issue you're facing with the "java.io.FileNotFoundException: No content provider" error might be due to incorrect handling of video URLs. Please make sure the video URLs are properly formatted and accessible.
英文:
I am creating something like a facebook post. Where a user can upload images and videos, and also view them. So I create an arrayList of the files and if the user click any image or video, it take them to a new activity to display all files in a viewpager, passing the arrayList and the index of the clicked file as parameters, so I can use the arrayList to set my adapter and the position of my viewpager to the index of the clicked file.
So here is my activity which displays the files
Bundle fileParams = getIntent().getExtras();
filePosition = fileParams.getInt("index");
allFiles = fileParams.getStringArrayList("arrayList");
photoOpenerAdapter = new PhotoOpenerAdapter(allFiles, cntxt);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(photoOpenerAdapter);
viewPager.setCurrentItem(filePosition);
viewPager.setOffscreenPageLimit(allFiles.size());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
viewPager.post(new Runnable() {
@Override
public void run() {
//loadedInitial is a boolean value to make this thread run only once
if(!loadedInitial) {
loadedInitial = true;
String filePath = allFiles.get(position);
String fileType = functions.getmInstance(cntxt).checkFileType(filePath);
if(fileType == "video")
startVideoPlayer(position);
}
}
});
}
@Override
public void onPageSelected(int position) {
pauseVideoPlayer();
String filePath = allFiles.get(position);
String fileType = functions.getmInstance(cntxt).checkFileType(filePath);
if(fileType == "video") {
startVideoPlayer(position);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
private void pauseVideoPlayer() {
if(!(videoView == null)){
videoView.pause();
}
}
public static void startVideoPlayer(int position) {
View videoLayout = viewPager.getChildAt(position);
videoView = (VideoView) videoLayout.findViewById(R.id.videoPlayer);
if(!(videoView == null)) {
videoView.requestFocus();
videoView.start();
}
}
}
And here is the instantiateItem
thread of my PhotoOpenerAdapter.java
class
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, final int position) {
layoutInflater = LayoutInflater.from(context);
String imageUrl = postFilesLists.get(position);
String fileType = functions.getmInstance(context).checkFileType(imageUrl.toLowerCase());
if(fileType == "video") {
view = layoutInflater.inflate(R.layout.video_player, container, false);
VideoView videoView = (VideoView) view.findViewById(R.id.videoPlayer);
Uri uri = Uri.parse(imageUrl);
videoView.setVideoURI(uri);
} else{
view = layoutInflater.inflate(R.layout.photo_opener, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
imageLoader.displayImage(imageUrl, imageView);
}
container.addView(view);
return view;
}
This code works fine but when the filePosition
is a video file, and I try to use the onPageScrolled
thread to load the video Url, I get the error java.io.FileNotFoundException: No content provider: http://
which is coming from the line Uri uri = Uri.parse(imageUrl);
, but if the filePosition
is an image file, and I scroll to a video file, onPageSelected
plays the video successfully.
Please I don't what am doing wrong
Here is the complete Stack Trace
04/07 11:30:40: Launching 'app' on Pixel 2 API 29.
$ adb shell am start -n "com.pixtanta.app/com.pixtanta.app.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Waiting for process to come online...
Connected to process 2259 on device 'Pixel_2_API_29 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/om.pixtanta.ap: Not late-enabling -Xcheck:jni (already on)
W/om.pixtanta.ap: Suspending all threads took: 11.490ms
E/om.pixtanta.ap: Unknown bits set in runtime_flags: 0x8000
W/om.pixtanta.ap: Unexpected CPU variant for X86 using defaults: x86
I/MultiDex: VM with version 2.1.0 has multidex support
Installing application
VM has multidex support, MultiDex support library is disabled.
W/RenderThread: type=1400 audit(0.0:270): avc: denied { write } for name="property_service" dev="tmpfs" ino=6344 scontext=u:r:untrusted_app:s0:c139,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 app=com.pixtanta.app
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/om.pixtanta.ap: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/om.pixtanta.ap: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
W/om.pixtanta.ap: Accessing hidden method Landroid/graphics/FontFamily;-><init>()V (greylist, reflection, allowed)
Accessing hidden method Landroid/graphics/FontFamily;->addFontFromAssetManager(Landroid/content/res/AssetManager;Ljava/lang/String;IZIII[Landroid/graphics/fonts/FontVariationAxis;)Z (greylist, reflection, allowed)
Accessing hidden method Landroid/graphics/FontFamily;->addFontFromBuffer(Ljava/nio/ByteBuffer;I[Landroid/graphics/fonts/FontVariationAxis;II)Z (greylist, reflection, allowed)
Accessing hidden method Landroid/graphics/FontFamily;->freeze()Z (greylist, reflection, allowed)
Accessing hidden method Landroid/graphics/FontFamily;->abortCreation()V (greylist, reflection, allowed)
Accessing hidden method Landroid/graphics/Typeface;->createFromFamiliesWithDefault([Landroid/graphics/FontFamily;Ljava/lang/String;II)Landroid/graphics/Typeface; (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xdf3462d0, tid 2311
HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xdf31a240: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xdf31a240: ver 2 0 (tinfo 0xdf30f110)
W/Gralloc3: mapper 3.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xdf346410, tid 2311
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2
D/eglCodecCommon: allocate: Ask for block of size 0x1000
allocate: ioctl allocate returned offset 0x3ffff6000 size 0x2000
D/EGL_emulation: eglMakeCurrent: 0xdf31a240: ver 2 0 (tinfo 0xdf30f110)
I/om.pixtanta.ap: Background concurrent copying GC freed 4031(1010KB) AllocSpace objects, 2(40KB) LOS objects, 52% free, 1374KB/2910KB, paused 470us total 316.229ms
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@5f8eb60
I/Choreographer: Skipped 34 frames! The application may be doing too much work on its main thread.
D/EGL_emulation: eglMakeCurrent: 0xdf31a240: ver 2 0 (tinfo 0xdf30f110)
W/om.pixtanta.ap: Verification of java.lang.String okio.internal.ByteStringKt.commonHex(okio.ByteString) took 232.844ms
I/OpenGLRenderer: Davey! duration=1006ms; Flags=1, IntendedVsync=10885691977642, Vsync=10886258644286, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=10886267267970, AnimationStart=10886267414940, PerformTraversalsStart=10886268302090, DrawStart=10886442318860, SyncQueued=10886448317080, SyncStart=10886459965410, IssueDrawCommandsStart=10886460230610, SwapBuffers=10886678824180, FrameCompleted=10886710235330, DequeueBufferDuration=75000, QueueBufferDuration=573000,
W/om.pixtanta.ap: Verification of java.lang.String okio.internal.ByteStringKt.commonToString(okio.ByteString) took 109.047ms
D/EGL_emulation: eglMakeCurrent: 0xdf31a240: ver 2 0 (tinfo 0xdf30f110)
I/chatty: uid=10139(com.pixtanta.app) RenderThread identical 2 lines
D/EGL_emulation: eglMakeCurrent: 0xdf31a240: ver 2 0 (tinfo 0xdf30f110)
W/om.pixtanta.ap: Verification of okio.Buffer okio.Buffer.writeUtf8(java.lang.String, int, int) took 103.361ms
W/om.pixtanta.ap: Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setUseSessionTickets(Z)V (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setHostname(Ljava/lang/String;)V (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->getAlpnSelectedProtocol()[B (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setAlpnProtocols([B)V (greylist,core-platform-api, reflection, allowed)
W/om.pixtanta.ap: Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (greylist,core-platform-api, reflection, allowed)
Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (greylist,core-platform-api, reflection, allowed)
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/om.pixtanta.ap: Verification of okio.Source okhttp3.internal.http1.Http1ExchangeCodec.newUnknownLengthSource() took 106.135ms
I/om.pixtanta.ap: NativeAlloc concurrent copying GC freed 8287(782KB) AllocSpace objects, 7(140KB) LOS objects, 49% free, 2343KB/4686KB, paused 1.498ms total 225.137ms
W/System: A resource failed to call close.
I/chatty: uid=10139(com.pixtanta.app) FinalizerDaemon identical 2 lines
W/System: A resource failed to call close.
V/MediaHTTPService: MediaHTTPService(android.media.MediaHTTPService@5dd4fad): Cookies: null
makeHTTPConnection: CookieManager created: java.net.CookieManager@a4fd2e2
makeHTTPConnection(android.media.MediaHTTPService@5dd4fad): cookieHandler: java.net.CookieManager@a4fd2e2 Cookies: null
I/om.pixtanta.ap: NativeAlloc concurrent copying GC freed 4930(489KB) AllocSpace objects, 23(460KB) LOS objects, 49% free, 2754KB/5508KB, paused 3.218ms total 327.970ms
W/System: A resource failed to call close.
I/chatty: uid=10139(com.pixtanta.app) FinalizerDaemon identical 2 lines
W/System: A resource failed to call close.
I/om.pixtanta.ap: JIT allocated 70KB for compiled code of void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int)
W/System: A resource failed to call close.
I/chatty: uid=10139(com.pixtanta.app) FinalizerDaemon identical 22 lines
W/System: A resource failed to call close.
I/OpenGLRenderer: Davey! duration=1410ms; Flags=0, IntendedVsync=10888523779635, Vsync=10888923779619, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=10888932055650, AnimationStart=10888932332760, PerformTraversalsStart=10888932378740, DrawStart=10889814355560, SyncQueued=10889856339460, SyncStart=10889856637920, IssueDrawCommandsStart=10889859104780, SwapBuffers=10889924611950, FrameCompleted=10889935046350, DequeueBufferDuration=92000, QueueBufferDuration=1623000,
I/om.pixtanta.ap: NativeAlloc concurrent copying GC freed 9429(653KB) AllocSpace objects, 15(300KB) LOS objects, 49% free, 3684KB/7369KB, paused 3.468ms total 426.579ms
W/System: A resource failed to call close.
I/chatty: uid=10139(com.pixtanta.app) FinalizerDaemon identical 7 lines
W/System: A resource failed to call close.
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@49b7a99
D/EGL_emulation: eglMakeCurrent: 0xdf31a240: ver 2 0 (tinfo 0xdf30f110)
W/MediaPlayer: Couldn't open http://192.168.58.1/...
java.io.FileNotFoundException: No content provider: http://192.168.58.1/uploads/video/PXT-IMG-1586206898-82ecc8ad45.mp4
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1673)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1503)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1420)
at android.media.MediaPlayer.attemptDataSource(MediaPlayer.java:1101)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1073)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1097)
at android.widget.VideoView.openVideo(VideoView.java:412)
at android.widget.VideoView.setVideoURI(VideoView.java:287)
at android.widget.VideoView.setVideoURI(VideoView.java:270)
at com.pixtanta.app.PhotoOpenerAct.startVideoPlayer(PhotoOpenerAct.java:102)
at com.pixtanta.app.PhotoOpenerAct$1.onPageSelected(PhotoOpenerAct.java:76)
at androidx.viewpager.widget.ViewPager.dispatchOnPageSelected(ViewPager.java:1947)
at androidx.viewpager.widget.ViewPager.scrollToItem(ViewPager.java:686)
at androidx.viewpager.widget.ViewPager.setCurrentItemInternal(ViewPager.java:670)
at androidx.viewpager.widget.ViewPager.onTouchEvent(ViewPager.java:2263)
at android.view.View.dispatchTouchEvent(View.java:13415)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3054)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2741)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:465)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1849)
at android.app.Activity.dispatchTouchEvent(Activity.java:3993)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:69)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:423)
at android.view.View.dispatchPointerEvent(View.java:13674)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5482)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5285)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4788)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4841)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4807)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4947)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4815)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5004)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4788)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4841)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4807)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4815)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4788)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7505)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7474)
W/MediaPlayer: at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7435)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7630)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:188)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:336)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
V/MediaHTTPService: MediaHTTPService(android.media.MediaHTTPService@983af96): Cookies: null
V/MediaHTTPService: makeHTTPConnection: CookieHandler (java.net.CookieManager@a4fd2e2) exists.
makeHTTPConnection(android.media.MediaHTTPService@983af96): cookieHandler: java.net.CookieManager@a4fd2e2 Cookies: null
D/MediaPlayerNative: getMetadata
W/MediaPlayerNative: info/warning (3, 0)
D/EGL_emulation: eglMakeCurrent: 0xdf31a240: ver 2 0 (tinfo 0xdf30f110)
V/MediaPlayer: resetDrmState: mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
cleanDrmObj: mDrmObj=null mDrmSessionId=null
resetDrmState: mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
cleanDrmObj: mDrmObj=null mDrmSessionId=null
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@24b04a0
D/EGL_emulation: eglMakeCurrent: 0xdf31a240: ver 2 0 (tinfo 0xdf30f110)
Process 2259 terminated.
答案1
得分: 0
最终,我搞定了...问题是在ViewPager加载适配器之前设置了ViewPager的当前项。所以我必须在ViewPager完成加载后设置它。
Bundle fileParams = getIntent().getExtras();
filePosition = fileParams.getInt("index");
allFiles = fileParams.getStringArrayList("arrayList");
photoOpenerAdapter = new PhotoOpenerAdapter(allFiles, cntxt);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(photoOpenerAdapter);
// 这里我移除了viewPager.setCurrentItem(filePosition),以便在ViewPager完成加载后设置它
viewPager.setOffscreenPageLimit(allFiles.size());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
viewPager.post(new Runnable() {
@Override
public void run() {
if (!loadedInitial) {
loadedInitial = true;
String filePath = allFiles.get(position);
String fileType = functions.getmInstance(cntxt).checkFileType(filePath);
if (fileType.equals("video"))
startVideoPlayer(position);
// 这里ViewPager已经加载完成,所以我调用方法来实现viewPager.setCurrentItem(filePosition)
setViewPagerCurrentItem();
}
}
});
}
@Override
public void onPageSelected(int position) {
pauseVideoPlayer();
String filePath = allFiles.get(position);
String fileType = functions.getmInstance(cntxt).checkFileType(filePath);
if (fileType.equals("video")) {
videoView = null;
startVideoPlayer(position);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
// 实现viewPager.setCurrentItem(filePosition)的方法
private void setViewPagerCurrentItem() {
viewPager.setCurrentItem(filePosition);
}
private void pauseVideoPlayer() {
if (!(videoView == null)) {
videoView.pause();
}
}
public static void startVideoPlayer(int position) {
View videoLayout = viewPager.getChildAt(position);
videoView = (VideoView) videoLayout.findViewById(R.id.videoPlayer);
if (!(videoView == null)) {
videoView.requestFocus();
videoView.start();
}
}
希望这对你有所帮助。
英文:
Finnaly I got it working... the problem was setting the ViewPager's current item before the ViewPager loaded the adapter. So I had to set that after the ViewPager has finished loading
Bundle fileParams = getIntent().getExtras();
filePosition = fileParams.getInt("index");
allFiles = fileParams.getStringArrayList("arrayList");
photoOpenerAdapter = new PhotoOpenerAdapter(allFiles, cntxt);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(photoOpenerAdapter);
//here I removed the viewPager.setCurrentItem(filePosition) to set it after the ViewPager has finished loading
viewPager.setOffscreenPageLimit(allFiles.size());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
viewPager.post(new Runnable() {
@Override
public void run() {
if(!loadedInitial) {
loadedInitial = true;
String filePath = allFiles.get(position);
String fileType = functions.getmInstance(cntxt).checkFileType(filePath);
if(fileType == "video")
startVideoPlayer(position);
// here the ViewPager has finished loading so I call the method to implement the viewPager.setCurrentItem(filePosition)
setViewPagerCurrentItem();
}
}
});
}
@Override
public void onPageSelected(int position) {
pauseVideoPlayer();
String filePath = allFiles.get(position);
String fileType = functions.getmInstance(cntxt).checkFileType(filePath);
if(fileType == "video") {
videoView = null;
startVideoPlayer(position);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
//Method to implement the viewPager.setCurrentItem(filePosition)
private void setViewPagerCurrentItem() {
viewPager.setCurrentItem(filePosition);
}
private void pauseVideoPlayer() {
if(!(videoView == null)){
videoView.pause();
}
}
public static void startVideoPlayer(int position) {
View videoLayout = viewPager.getChildAt(position);
videoView = (VideoView) videoLayout.findViewById(R.id.videoPlayer);
if(!(videoView == null)) {
videoView.requestFocus();
videoView.start();
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论