1

I'm trying to call a function to open a browser with a given url but get this error message.

I looked at those two question and understand I probably have a context problem but still couldn't quite understand how to resolve it.

Cannot resolve method startActivity()

Cannot find symbol method startActivity(android.content.Intent)

My code:

public void openWeb(String url) {
    String fullUrl = "http://bit.do/"+url;
    Uri webpage = Uri.parse(fullUrl);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}
Community
  • 1
  • 1
Voly
  • 145
  • 4
  • 16

5 Answers5

3

This means that this method is in a class that does not have access to a context. So you can either pass the context from the activity that uses this method or place this method within the class of that activity.

Daniel
  • 2,355
  • 9
  • 23
  • 30
3

You shall get a context from the constructor like this:

public class YourClass{
   private Context context;

   public YourClass(Context context) {
       this.context = context;
   }
   ...
   public void openWeb(String url) {
      String fullUrl = "http://bit.do/"+url;
      Uri webpage = Uri.parse(fullUrl);
      Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
      if (intent.resolveActivity(getPackageManager()) != null) {
         context.startActivity(intent);
      } 
   }

}
Mark Shen
  • 346
  • 1
  • 5
0
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41
0

It seems that you will have to pass the uri using intent.setData. Try doing this way,

String url = "your url";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Mit
  • 318
  • 2
  • 10
-1

Assuming you are using fragment

Try :

getActivity().startActivity(i);

Here getActivity() returns the context

Vivek_Neel
  • 1,343
  • 1
  • 14
  • 25