Uri文件大小始终为0

时间:2017-08-09 11:44:47

标签: java android uri

我收到一个我保存在uri (android.net.Uri)

中的音频文件

我需要在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.

我该如何解决?

1 个答案:

答案 0 :(得分:1)

最后我修理了这个:

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所说的,但没有理由解释......

无论如何,这是一个可行的解决方案,希望对其他用户也很有用