2015-10-19 2 views
0

Я хочу создать приложение, которое имеет функцию загрузки файла. Но проблема в том, что я не могу найти, где я ошибся.Анализ: невозможно загрузить файл

Во-первых, выберите файл

public void onClick(View arg0) { 

      Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
      intent.setType("*/*"); 
      // intent.addCategory(Intent.CATEGORY_OPENABLE); 

      try { 
       Log.d(TAG, "Select file"); 
       startActivityForResult(
         Intent.createChooser(intent, "Select a File to Upload"), 
         RESULT_LOAD_FILE); 
      } catch (android.content.ActivityNotFoundException ex) { 
       // Potentially direct the user to the Market with a Dialog 
       Toast.makeText(MainActivity.this, "Please install a File Manager.", Toast.LENGTH_SHORT).show(); 
      } 

      // here 
     } 

Я предполагаю, что нет никаких проблем при выборе файла на основе LogCat. Но ...

public void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    super.onActivityResult(requestCode, resultCode, data); 
    Log.d(TAG, requestCode+"/"+RESULT_LOAD_FILE+"/"+resultCode+"/"+RESULT_OK); 

    if (data != null) Log.d(TAG, data.toString()); 
    else Log.d(TAG, "data null"); 

    // get file name 
    String fileNameSegments[] = filePath.split("/"); 
    fileName = fileNameSegments[fileNameSegments.length - 1]; 

    // convert it to byte 
    byte[] fileByte = fileName.getBytes(); 

    // Create the ParseFile 
    ParseFile file = new ParseFile(fileName, fileByte); 

    // Upload the image into Parse Cloud 
    file.saveInBackground(); 

    // Create a New Class called "ImageUpload" in Parse 
    ParseObject fileupload = new ParseObject("FileUpload"); 

    // Create a column named "ImageName" and set the string 
    fileupload.put("FileName", fileName); 

    // Create a column named "ImageFile" and insert the image 
    fileupload.put("DocFile", file); 

    // Create the class and the columns 
    fileupload.saveInBackground(); 

    // Show a simple toast message 
    Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show(); 
} 

LogCat шоу requestCode, RESULT_LOAD_FILE, resultCode и RESULT_OK 1, 1, -1 и -1 соответственно. И данные не являются нулевыми, как в logcat: Intent { dat=content://com.android.externalstorage.documents/document/0A09-1112:Download/Contact n Tort.pdf flg=0x1 }

После того, как я щелкнул файл .pdf, он вызвал тост Something went wrong, но я не могу найти причину.


Редакция: Throw Исключения нулевого указателя после преобразования пути к файлу в байте, когда я удалить блок попытаться поймать

+0

Что такое сообщение для исключения? –

+0

@MoNazemi 'Ошибка выдачи результата ResultInfo {who = null, request = 1, result = -1, data = Intent {dat = content: ..........}} в действие {com.example .. ......... MainActivity}: java.lang.NullPointerException: попытка вызвать виртуальный метод «java.lang.String [] java.lang.String.split (java.lang.String)» на нулевом объекте reference' – August

+0

Ну, это говорит, что переменная 'filePath' равна null, где вы инициализируете это? –

ответ

0

это должно быть, как это

Uri uri = data.getData(); 
      // get path 
      filePath = uri.getPath(); 

      // get file name 
      String fileNameSegments[] = filePath.split("/"); 
      fileName = fileNameSegments[fileNameSegments.length - 1]; 

      // convert it to byte 
      byte[] fileByte = fileName.getBytes(); 

      // Create the ParseFile 
      ParseFile file = new ParseFile(fileName, fileByte); 

      // Upload the file into Parse Cloud 
      file.saveInBackground(); 

      // Create a New Class called "FileUpload" in Parse 
      ParseObject fileUpload = new ParseObject("FileUpload"); 

      // Create a column named "FileName" and set the string 
      fileUpload.put("FileName", fileName); 

      Log.d(TAG, "image file"); 
      // Create a column named "ImageFile" and insert the image 
      fileUpload.put("DocFile", file); 

      // Create the class and the columns 
      fileUpload.saveInBackground(); 

      Log.d(TAG, "toast"); 
      // Show a simple toast message 
      Toast.makeText(MainActivity.this, "File Uploaded", 
        Toast.LENGTH_SHORT).show(); 

хотя класс не создало в parse dashboard, но я предполагаю, что нужен другой пост.

Смежные вопросы