Reputation:
How to open .png or .doc file in android in new Activity.
Upvotes: 2
Views: 11595
Reputation: 1440
I know that this question was asked a long time a go (Kotlin wasn't even born :) ) but maybe someone will find useful my answer.
If you want to open an image (.png, .jpg, .jpeg) or a file (.doc or .docx) then you could do this:
JAVA
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
String[] mimeTypes = {"image/*", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
startActivityForResult(intent, YOUR_REQUEST_CODE);
Then in the onActivityResult
method:
if (requestCode == YOUR_REQUEST_CODE && resultCode == RESULT_OK) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (data != null && data.getData() != null) {
if (data.getData().toString().contains(".png") ||
data.getData().toString().contains(".jpg") ||
data.getData().toString().contains(".jpeg")) {
intent.setDataAndType(data.getData(), "image/jpeg");
} else if (data.getData().toString().contains(".doc")) {
intent.setDataAndType(data.getData(), "application/msword");
} else if (data.getData().toString().contains(".docx")) {
intent.setDataAndType(data.getData(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
}
}
startActivity(intent);
}
KOTLIN
startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
type = "*/*"
val mimeTypes = arrayOf(
"image/*",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
}
, YOUR_REQUEST_CODE)
Then in the onActivityResult function:
if (requestCode == YOUR_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
startActivity(Intent(Intent.ACTION_VIEW).apply {
flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
if (data?.data.toString().contains(".png") ||
data?.data.toString().contains(".jpg") ||
data?.data.toString().contains(".jpeg")
) {
setDataAndType(data?.data, "image/jpeg")
} else if (data?.data.toString().contains(".doc")) {
setDataAndType(data?.data, "application/msword")
} else if (data?.data.toString().contains(".docx")) {
setDataAndType(
data?.data,
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
}
})
}
Upvotes: 0
Reputation: 47514
With PNGs you can use an ImageView.
There isn't really any way to read DOC files unless you want to write a parser yourself. You could try Apache POI, but you'll still have to draw it to the screen yourself.
Upvotes: 1