Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

android - Can't check if file on sdcard exists

I'm trying to make a simple check if the file exist. I saw similar questions here, but they didn't help. When I run my application, the app crashes and I got message "Unfortunatelly, fileCheck1 has stopped". I got this error both on emulator and smartphone.

My code:

package com.example.fileCheck1;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;

import java.io.File;

public class MyActivity extends Activity {

    TextView msgText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        msgText = (TextView) findViewById(R.id.textView);
        String Path = Environment.getExternalStorageDirectory().getPath()+"/ping.xml";
        File file = getBaseContext().getFileStreamPath(Path);
        if(file.exists()){
            msgText.setText("Found");
        }
        if(!file.exists()){
            msgText.setText("Not Found");
        }
    }
}

In my Manifest such permissions:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think that problem is here:

getBaseContext()

where it is assigned to NULL. You really don't need this line. You can simply achieve your goal with

String path = Environment.getExternalStorageDirectory().getPath() + "/ping.xml";
File f = new File(path);
if (f.exists()) {
   // do your stuff
}
else {
  // do your stuff
}

Update:

If you or someone else have Samsung Galaxy S3, please follow @Raghunandan's answer because in this case getExternalStorageDirectory() returns internal memory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...