Robert
Robert

Reputation: 343

Call an activity from non activity class

I want to call an activity from a non activity class and base class send some arguments as bundle. But when I add the following code

 final Intent intent = new Intent(UserSettingsFragment.this, UserAccount.class);
  /*Sending some arguments*/ 
  Bundle bundle = new Bundle();
   bundle.putString("UserName",NAME);
   bundle.putString("Id", ID);
   intent.putExtras(bundle);
   this.startActivity(intent);`

eclipse shows the error

  The constructor `Intent(UserSettingsFragment, Class<UserAccount>) is undefined.

How can I solve this problem.

Upvotes: 0

Views: 1503

Answers (3)

Chintan Khetiya
Chintan Khetiya

Reputation: 16162

Case 1

  • I have use other alternative in my case like pass Activity or Context in to constructor and using that context you can call your Next activity.

Case 2

  • I think you should use Interface and that callback will change your activity as per your response.

  • Write Callback method inside ABC interface and implement ABC in some other Java file which should extend Activity or Fragment Activity.

  • So that Override method will automatically call your event when some particular task will finish at some time.

  • I think this is easy and best way to call Intent from non extend Activity class.

  • See How to manage this with simple example here

Upvotes: 4

Serj Lotutovici
Serj Lotutovici

Reputation: 4380

As @Gooziec said:

You need to rewrite you code this way:

// If you are calling this for in a Fragment.
final Intent intent = new Intent(getActivity(), UserAccount.class);
/*Sending some arguments*/ 
Bundle bundle = new Bundle();
bundle.putString("UserName",NAME);
bundle.putString("Id", ID);
intent.putExtras(bundle);
this.startActivity(intent);`

The Intent constructor you are using requires a Context as first parameter. Please refer to the documentation.

Upvotes: 2

Gooziec
Gooziec

Reputation: 2776

use getActivity() instead of UserSettingsFragment.this.

I guess you try start another activity from fragment. If so, then you have to pass context of parent's Activity of the fragment to Intent constructor

Upvotes: 1

Related Questions