0

I want to show csv file in a viewer when a csv viewer installed in phone. otherwise I need to show a toast message "There is no CSV viewer installed".

In my case, when I test below code in a device with no csv viewer installed in it.

I am not getting ActivityNotFoundException. as a result, my toast message was not shown. could you please help

            Uri uri = Uri.parse(pdfUrl);
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "text/csv");
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getActivity(), "There is no CSV viewer installed", Toast.LENGTH_SHORT).show();
            }
Ananth
  • 115
  • 3
  • 18

3 Answers3

1

using this SO answer, you can go through a different behaviour:

Instead of trying to start the activity and catching the ANF exception (which could be problematic, as there are flows that won't throw that exception), you can check ahead if the intent will be handled.

use this Java code: (assuming this inherit from Activity)

Activity activity = this; // change this line if calling from other places (a fragment etc)
Uri uri = Uri.parse(pdfUrl);
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/csv");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

if (intent.resolveActivity(activity.getPackageManager()) == null) {
    // No Activity found that can handle this intent.
    Toast.makeText(activity, "There is no CSV viewer installed", Toast.LENGTH_SHORT).show();
}
else{
    // There is an activity which can handle this intent.
    activity.startActivity(intent);
}
Re'em
  • 1,869
  • 1
  • 22
  • 28
0

Toast showing length is wrong:

Toast.makeText(getActivity(), "There is no CSV viewer installed", Toast.LENGTH_SHORT).show();

You have to use Toast.LENGTH_SHORT instead of Toast.short

Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
0

You can open intent chooser which contains an application that handles CSV files.

startActivity(Intent.createChooser(intent, "Select Application"));

if there is no application installed which handles CSV file it will show no application installed.