1

I am developing an app in which i want to launch any application installed on my device. I have tried the following code.

Button bClock = (Button) findViewById(R.id.button1);
String app="com.whatsapp";
bClock.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    Intent i = new Intent(Intent.ACTION_MAIN);
    PackageManager managerclock = getPackageManager();
    i = managerclock.getLaunchIntentForPackage(app);
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    startActivity(i);
  }
});

It shows error:

Cannot refer to a non-final variable app inside an inner class defined in a different method

But if I directly use "com.whatsapp" instead of storing in String, it is working. Help me to solve this issue

Mihriban Minaz
  • 3,043
  • 2
  • 32
  • 52
luna
  • 41
  • 1
  • 1
  • 5
  • issue with final variable. just declare the string app as global and refer in your button click – Ameer Mar 27 '16 at 06:25
  • what do you mean by " refer in your button click" can you explain it in detail. I am new to android – luna Mar 27 '16 at 07:37
  • check shree krishna's answer. – Ameer Mar 27 '16 at 09:28
  • Possible duplicate of [Launch an application from another application on Android](https://stackoverflow.com/questions/3872063/launch-an-application-from-another-application-on-android) – Mehdi Dehghani Apr 18 '19 at 12:22

2 Answers2

3

For your code correction please make String app="com.whatsapp"; a final variable or you can use package name directly like following

You should use the function of the package manager.

Context ctx=this; // or you can replace **'this'** with your **ActivityName.this**
try {
Intent i = ctx.getPackageManager().getLaunchIntentForPackage("com.whatsapp");
ctx.startActivity(i);
} catch (NameNotFoundException e) {
    // TODO Auto-generated catch block
}
Adnan Amjad
  • 2,553
  • 1
  • 20
  • 29
  • thanks it works. But in my case, the application has to be chosen from the spinner . So I have used String to strore the package name – luna Mar 27 '16 at 07:24
1

If so then make it final

final String app="com.whatsapp";

OR

Declare it as global variable of class like

public class MyClass {

String app="com.whatsapp";

//Other methods
}
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68