0

Suppose I have two Activity(under the same package):

HomeActivity(The launcher activity)

SpinnerActivity

Both of them are registered at the AndroidManifest.xml.

Now I try to create a method to implement the activity jump:

private void redirectToActivity(String dest) {
    Intent intent = new Intent();
    intent.setClassName(this,dest);
    startActivity(intent);
}

And I call it in the HomeActivity:

redirectToActivity("SpinnerActivity");

But I got this error:

Unable to find explicit activity class {com.app/SpinnerActivity}; have you declared this activity in your AndroidManifest.xml?

I tried to add this line:

intent.setPackage("com.app");

It does not work.

What's the problem?

hguser
  • 35,079
  • 54
  • 159
  • 293
  • Instead of using String maybe you could use Class variable ? – An-droid Aug 20 '13 at 08:31
  • Can you post your manifest file ? If your activity name in the manifest is ".SpinnerActivity", try to start it with : redirectToActivity(".SpinnerActivity"); – nbe_42 Aug 20 '13 at 08:34
  • See if changing `intent.setClassName(this,dest);` to `intent.setClassName(getApplicationContext(), dest);` works. – Vikram Aug 20 '13 at 08:36
  • @Yume117:I have to use the string because I get the activity name by user selecting through a ListView. – hguser Aug 20 '13 at 08:36
  • @nbe_42: Yes, in the manifest it is ".SpinnerActivity", I have changed to `redirectToActivity(".SpinnerActivity")`, I still got the same error. – hguser Aug 20 '13 at 08:38
  • @vikram: I have tried and I got the same error. – hguser Aug 20 '13 at 08:38
  • Here is what i meant http://stackoverflow.com/questions/5754855/how-can-i-start-a-new-android-activity-using-a-string – An-droid Aug 20 '13 at 08:38

2 Answers2

1
Unable to find explicit activity class {com.app/SpinnerActivity}; have you declared this activity in your AndroidManifest.xml?

your package-name is odd. i am used to something like "com.company.appname" and you got com.app/SpinnerActivity. Have you tried thinking in that direction?

bofredo
  • 2,348
  • 6
  • 32
  • 51
  • Since this is a application for learning android. So I use the `com.app` as the package name, does this matter? – hguser Aug 20 '13 at 08:41
1

// Define it globally or in OnCreate() method

// If your all Activity is with in the same package then this approach is going to work.

final String packageName = this.getClass().getPackage().getName();
final Context context = this;

// call your method like this i.e SpinnerActivity
         private void redirectToActivity(String dest) {

                  try {
                        Class c = Class.forName(packageName + "." + dest);
                        startActivity(new Intent(context, c));
                    } catch (ClassNotFoundException e) {
                        Toast.makeText(context, String.valueOf(e), 5000).show();
                    }
           }
Amit Gupta
  • 8,914
  • 1
  • 25
  • 33