samedi 31 octobre 2015

Android read text file in Activity that filters opening text files

I have Activity that "listening" to open text files, which means in manifest:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/*" />
</intent-filter>

So I navigate to file browser, find some text file and try to open it, and as expected this Activity exists on the list of available applications to complete the action. When the activity launches I know the Activity got the correct file name but it treats the file as empty (not printing to the log the content).

Remarks: The file is not empty, other apps can read him, the file path not contains white spaces, no exceptions or crashes.

What i'm doing wrong here?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    //Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    if (Intent.ACTION_VIEW.equals(action) && type != null && "text/plain".equals(type)) {
        handleViewText(intent);  //Handle text being sent
    }
}

private void handleViewText(Intent intent) {
    Uri uri = intent.getData();
    BufferedReader br = null;
    try {
        String sCurrentLine;
        InputStream is = getContentResolver().openInputStream(uri);
        br = new BufferedReader(new InputStreamReader(is));
        //This is also not working: br = new BufferedReader(new FileReader(uri.getPath()));
        while ((sCurrentLine = br.readLine()) != null) {
            Log.e("TAG", sCurrentLine);  //never enters here
        }
    } catch (Exception e) {
        //nothing
    } finally {
        try {
            if (br != null) br.close();
        } catch (Exception e) {
            //nothing
        }
    }
}  

Aucun commentaire:

Enregistrer un commentaire