2014-11-03 1 views
0

메신저 이미지를 사용자 폰에 다운로드하는 응용 프로그램을 개발 중입니다. 다운로드 부분이 올바르게 작동하고 이미지가 "/ Android/data // files /"에 저장됩니다. 먼저 파일이 존재하는지 확인한 다음 그 파일을 다운로드하고 싶습니다. 내가 응용 프로그램을 실행할 때 그러나 그것은 NullpointerException이 .is는 던져 계속 그 때문에 "/ 안드로이드/데이터 // 파일 /"내가이 문제를 해결하려면 어떻게 그렇다면은? 첫 번째 실행 시간 동안 존재하지 않습니다.파일이있는 경우 dir을 확인하는 방법은 무엇입니까?

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    testtv = (TextView) findViewById(R.id.testtv); 
    String imagename = "/img11.png"; 
    File image = new File(Environment.getExternalStorageDirectory() 
      .getAbsolutePath() 
      + "/Android/data/com.id.imagedownloader/files" + imagename); 
    // testtv.setText(image.toString()); 

    if (image.exists()) { 
     testtv.setText("file exists"); 
    } else { 
     Boolean result = isDownloadManagerAvailable(getApplicationContext()); 
     if (result) { 
      downloadFile(imagename); 
     } 
    } 

} 

@SuppressLint("NewApi") 
public void downloadFile(String imagename) { 
    // TODO Auto-generated method stub 
    String DownloadUrl = "http://testing16.comlu.com/images/" + imagename; 
    DownloadManager.Request request = new DownloadManager.Request(
      Uri.parse(DownloadUrl)); 
    request.setDescription("sample file for testing"); // appears the same 
                 // in Notification 
                 // bar while 
                 // downloading 
    request.setTitle("Test Title"); 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
     request.allowScanningByMediaScanner(); 
     request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
    } 
    String fileName = DownloadUrl.substring(
      DownloadUrl.lastIndexOf('/') + 1, DownloadUrl.length()); 
    request.setDestinationInExternalFilesDir(getApplicationContext(), null, 
      fileName); 

    // get download service and enqueue file 
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
    manager.enqueue(request); 

} 

public static boolean isDownloadManagerAvailable(Context context) { 
    try { 
     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { 
      return false; 
     } 
     Intent intent = new Intent(Intent.ACTION_MAIN); 
     intent.addCategory(Intent.CATEGORY_LAUNCHER); 
     intent.setClassName("com.android.providers.downloads.ui", 
       "com.android.providers.downloads.ui.DownloadList"); 
     List<ResolveInfo> list = context.getPackageManager() 
       .queryIntentActivities(intent, 
         PackageManager.MATCH_DEFAULT_ONLY); 
     return list.size() > 0; 
    } catch (Exception e) { 
     return false; 
    } 
} 

로그 캣

11-03 14:13:35.821: E/AndroidRuntime(771): FATAL EXCEPTION: main 
11-03 14:13:35.821: E/AndroidRuntime(771): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.id.imagedownloader/com.id.imagedownloader.MainActivity}: java.lang.NullPointerException: file 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.access$600(ActivityThread.java:122) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.os.Handler.dispatchMessage(Handler.java:99) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.os.Looper.loop(Looper.java:137) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.main(ActivityThread.java:4340) 
11-03 14:13:35.821: E/AndroidRuntime(771): at java.lang.reflect.Method.invokeNative(Native Method) 
11-03 14:13:35.821: E/AndroidRuntime(771): at java.lang.reflect.Method.invoke(Method.java:511) 
11-03 14:13:35.821: E/AndroidRuntime(771): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
11-03 14:13:35.821: E/AndroidRuntime(771): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
11-03 14:13:35.821: E/AndroidRuntime(771): at dalvik.system.NativeStart.main(Native Method) 
11-03 14:13:35.821: E/AndroidRuntime(771): Caused by: java.lang.NullPointerException: file 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.net.Uri.fromFile(Uri.java:441) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.DownloadManager$Request.setDestinationFromBase(DownloadManager.java:504) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.DownloadManager$Request.setDestinationInExternalFilesDir(DownloadManager.java:466) 
11-03 14:13:35.821: E/AndroidRuntime(771): at com.id.imagedownloader.MainActivity.downloadFile(MainActivity.java:63) 
11-03 14:13:35.821: E/AndroidRuntime(771): at com.id.imagedownloader.MainActivity.onCreate(MainActivity.java:40) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.Activity.performCreate(Activity.java:4465) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919) 
11-03 14:13:35.821: E/AndroidRuntime(771): ... 11 more 
+1

어쩌면'시도 {...} 캐치 (IOException이 전자) {...}' – jyoon

+0

밤은 방법 downloadFile에서 오는 예외? com.id.imagedownloader.MainActivity.downloadFile (MainActivity.java:63), 외부 저장소에 대상을 설정 한 경우 해당 폴더가 있는지 확인한 다음 작동해야합니다 (최소한 내가 본 것으로부터) – Michael

+0

해당 보증하지 않습니다. 외부 저장소가 존재 함 – for3st

답변

0

설정 응용 프로그램의 외부 파일 내에서 경로에 다운로드 한 파일

request.setDestinationInExternalFilesDir(context,Environment.DIRECTORY_DOWNLOADS,image); 

이 mkdirs와 DIRS를 작성하는 것을 잊지 말아 디렉토리에 대한 로컬 대상() 상위 폴더가없는 경우

+0

다운로드 기능을 사용하여 코드를 업데이트했습니다. –

0

setDestinationInExternalFilesDir에는 dirType 매개 변수가 필요합니다. 다음과 같이 사용해야합니다 :

request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS, 
     fileName); 
-1

이 기능을 사용하면 바이트 배열에서 파일을 만들고이 파일이 있는지 확인할 수 있습니다. 다음과 같이 시도해보십시오.

/** 
* Create new file from byte array 
* @param path 
* @param array source 
* @throws IOException 
*/ 
public static void writeFile(String path, byte[] array) throws IOException { 
    File file = new File(path); 
    if (!file.exists() && array != null) { 
     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); 
     bos.write(array); 
     bos.flush(); 
     bos.close(); 
    } else { 
     // the file exists... 

    } 
} 

희망이 있습니다.

+0

CM11을 실행하는 내 GS3에서 코드를 테스트했는데 제대로 작동합니다. 에뮬레이터에서 충돌 만 발생합니다. 왜 그런가요? –

+0

외부 저장소에 파일을 저장하려고하면 충돌이 발생할 수 있습니다. –

+0

logcat 추적을 추가 할 수 있습니까? –

관련 문제