2017-08-09 81 views
1

我得到我在一個uri (android.net.Uri)烏里文件大小始終爲0

我需要顯示它在一個TextView尺寸正在挽救一個音頻文件。我想是這樣的:

這是我得到的用戶庫文件:

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.debug_layout); 

     Intent selectIntent = new Intent(Intent.ACTION_GET_CONTENT); 
     selectIntent.setType("audio/*"); 
     startActivityForResult(selectIntent, AUDIO_REQUEST_CODE); 

    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == AUDIO_REQUEST_CODE && resultCode == Activity.RESULT_OK) { 
      if ((data != null) && (data.getData() != null)) { 
       audio = data.getData(); 
      } 
     } 
    } 

然後我把它傳遞給下一個活動是這樣的:

Intent debugIntent = new Intent(this, Debug.class); 
     Bundle bundle = new Bundle(); 
     bundle.putString("audio", audio.toString()); 
     debugIntent.putExtras(bundle); 
     startActivity(debugIntent); 

而且在使用它調試活動是這樣的:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.debug_layout); 

    Intent intent = this.getIntent(); 
    Bundle bundle = intent.getExtras(); 
    audio = Uri.parse((String) bundle.get("audio")); 

    File file = new File(audio.getPath()); 
    long size = file.length(); 
    if (file.exists()) { 
     Toast.makeText(this, "exists", Toast.LENGTH_SHORT).show(); 
    } 
    filesize = (TextView) findViewById(R.id.file_size); 
    filesize.setText("file size: ".concat(String.valueOf(size))); 

} 

file.length()返回0。

我該如何解決這個問題?

+2

如果文件不存在,file.length()將返回0L(https://developer.android.com/reference/java/io/File.html#length() )。確保你的文件存在,你可以使用file.exists()方法。 – daniftodi

+0

你如何初始化音頻? – bendaf

+0

@daniftodi你是對的。文件接縫不存在。任何線索爲什麼會發生這種情況? – Daniele

回答

0

最後我固定它是這樣的:

private String getRealSizeFromUri(Context context, Uri uri) { 
     Cursor cursor = null; 
     try { 
      String[] proj = { MediaStore.Audio.Media.SIZE }; 
      cursor = context.getContentResolver().query(uri, proj, null, null, null); 
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE); 
      cursor.moveToFirst(); 
      return cursor.getString(column_index); 
     } finally { 
      if (cursor != null) { 
       cursor.close(); 
      } 
     } 
    } 

我想這是在評論什麼pskink說的話,但沒有刻意去解釋......

反正這是一個可行的解決方案這對其他用戶也有用