public void changeActivity(Context context){
Intent intent =new Intent(this,context.getClass());
startActivity(intent);
finish();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.register:
changeActivity(RegisterActivity);
break;
}
}
I am using a 'changeActivity' method but I got error in line 10. The error pointed that 'Expression Expected'
You're not passing your class file as object to Intent when you start activity.
Find out below solution :
public void changeActivity(Class<? extends Activity> context) { // Receive it here and provide to your intent.
Intent intent =new Intent(this, context);
startActivity(intent);
finish();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.register:
changeActivity(RegisterActivity.class); // pass object of your desired activity as class parameter here
break;
}
}
You have pass an class object of your desination activity in your changeActivity method like this:
public void changeActivity(Class<? extends Activity> desinationActivity) {
Intent intent = new Intent(this, destinationActivity);
startActivity(intent);
finish();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.register:
changeActivity(RegisterActivity.class);
break;
}
}
You can check out this link for reference. Hope this helps.
For writing this type of code you can check system source code. Following code of Intent constructor:
public Intent(Context packageContext, Class<?> cls) {
mComponent = new ComponentName(packageContext, cls);
}
Related
I am newbie in app development.In my project have lot of Explicit Intent so i want to make a public method which argument contains conext or a class where i want to jump but it's not working is there have who know the proper solution for it.
Here is my method where i call my public intent class.
private void startActivityMethod() {
if (progressStatus == 100) {
if (firebaseUser != null) {
if (sp.getString(Constants.userType, "").equals("student")) {
Constants.explicitIntent(SplashActivity.this, studentMainActivity.class);
} else if (sp.getString(Constants.userType, "").equals("faculties")) {
Constants.explicitIntent(SplashActivity.this, facultiesMainActivity.class);
}
} else {
startActivity(new Intent(SplashActivity.this, LoginActivity.class));
finish();
}
}
}
Here is my public class method for intent.
public static void explicitIntent(Context context, Class<?> intentClass) {
Intent intent =new Intent(context,intentClass);
}
You should call startActivity to launch the intent
public static void explicitIntent(Context context, Class<?> intentClass) {
Intent intent =new Intent(context, intentClass);
context.startActivity(intent);
}
I am working on an online radio app demo. I've created an error Activity which I want to take the user to, when an error occurs. In the error page, there is a refresh button, which is supposed to refresh the last Activity where an error occurred. But I don't know how to get the Intent of previous Activity which led to the error page to get it refresh on ButtonClick, I only know to make it return to a particular Activity.
You can use startActivityForResult in both calling activities
In MainActivity.java
int REFRESH = 1;
private void startErrorActivity() {
startActivityForResult(new Intent(this, ErrorActivity.class), REFRESH);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REFRESH) {
//do refresh
}
}
And in ErrorActivity.java
Button button = findViewById(R.id.refreshButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish(); //this will take you back to calling activities onActivityResult method
}
});
UPDATE:
I honestly think #sneharc's answer is better. Use that.
Try this:
public class ActivityA extends Activity {
public void myFunction(){
try{
// something bad happens here. need to go to ErrorActivity
}
catch (SomeException e){
Intent startErrorActivityIntent = new Intent(this, ErrorActivity.class);
startErrorActivityIntent.putExtra("sourceActivity", ActivityA.class.getSimpleName())
startActivity(this, startErrorActivityIntent)
}
}
}
public class ActivityB extends Activity {
public void myFunction(){
try{
// something bad happens here. need to go to ErrorActivity
}
catch (SomeException e){
Intent startErrorActivityIntent = new Intent(this, ErrorActivity.class);
startErrorActivityIntent.putExtra("sourceActivity", ActivityB.class.getSimpleName())
startActivity(this, startErrorActivityIntent)
}
}
}
public class ErrorActivity extends Activity {
private Intent mReceivedIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
mReceivedIntent = getIntent();
}
public void onClickRefresh(){
String retryActivityName = mReceivedIntent.getStringExtra("sourceActivity");
Intent retryActivityIntent = null;
if (!TextUtils.isEmpty(retryActivityName)){}
if (retryActivityName.equalsIgnoreCase(ActivityA.class.getSimpleName()))
retryActivityName = new Intent(this, ActivityA.class);
if (retryActivityName.equalsIgnoreCase(ActivityB.class.getSimpleName()))
retryActivityName = new Intent(this, ActivityB.class);
}
if (retryActivityIntent != null)
startActivityForResult(this, retryActivityIntent);
}
}
Here is the code for back button. I want to kill other activities by back button but its not working in one activity, but I have other activities and without one activity its working fine. Please help me out.
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
Might be this code will help you:
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SomeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
You have to set Flags according to API level :
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
if(Build.VERSION.SDK_INT >= 11)
{
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
else
{
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
startActivity(intent);
Hope it helps ツ
You can set android:noHistory="true" in activities tag in AndroidManifest.xml which you don't want to save in stack.
Try to define one local broadcast receiver on top most parent activity or base activity :
private final class KillReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
}
Intialize and register broadcast receiver in onCreate() and unregister in onDestroy() on top most parent activity or base activity :
private KillReceiver clearActivityStack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
clearActivityStack = new KillReceiver();
registerReceiver(clearActivityStack, IntentFilter.create("clearStackActivity", "text/plain"));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(clearActivityStack);
}
Now call broadcast receiver when wan to clear all previous activity :
public void onClick(View v) {
Intent clearIntent = new Intent("clearStackActivity");
clearIntent.setType("text/plain");
sendBroadcast(clearIntent);
Intent intent = new Intent(getApplicationContext(),SomeActivity.class);
startActivity(intent);
}
I have an android app. When the user clicks button A and intent is fired like this android-presudocode :)
//inside FirstActivity
#Override
public void onClick(View view) {
startActivity(new Intent(this, AnotherActivity.class));
}
So if I'm not mistaken, the onResume method in AnotherActivity should be called, right?
I use ActivityInstrumentationTestCase2<FirstActivity> to test my activity but I'm unable to instantiate AnotherActivity.
So the question is, how can I test this: 'When a button is pressed, the correct activity is resumed and the correct extras are passed to the intent'.
You can use the instrumentation to make an ActivityMonitor. This will monitor if a new activity has been started.
ActivityMonitor am = getInstrumentation().addMonitor(Activity3.class.getName(), null, true;
Then you want to use button.performClick() to "press the button". Finally, you check if the activity monitor has been hit.
am.waitForActivitywithTimeout(timeout);
assertEquals(1, am.getHits());
I haven't used ActivityInstrumentationTestCase2 in quite a while so I don't guarantee these steps are exactly right. In any case, I recommend that you take a look at Robolectric: a wonderful unit testing framework for Android that will change your life. It will help you overcome many situations that are difficult or impossible to test with any of the default instrumentation tests.
So after some time I want to post the solution that I use almost always.
Initially I liked #aleph_null's solution but it turns out that it makes tests unbearably slow so this is what I use now:
First, I have this interface
/**
* Simple interface to launch other activities.
*/
public interface ActivityLauncher {
/**
* Starts an activity with the Intent provided.
* #param intent an intent
*/
public void start(Context context, Intent intent);
/**
*
* Returns the intent as set by {#link #start(android.content.Context, android.content.Intent) start} or null if not yet
* called.
*
* #return an intent or null
*/
public Intent getIntent();
}
And I have two implementations for it:
/**
* Default implementation of ActivityLauncher
*/
public class DefaultActivityLauncher implements ActivityLauncher{
private Intent intent;
public DefaultActivityLauncher(){}
#Override
public void start(Context context, Intent intent) {
this.intent = intent;
context.startActivity(intent);
}
#Override
public Intent getIntent() {
return intent;
}
}
and
/**
* Mock implementation of ActivityLauncher that simply sets the intent but does not actually starts
* an activity.
*/
public class MockActivityLauncher implements ActivityLauncher {
private Intent intent;
#Override
public void start(Context context, Intent intent) {
this.intent = intent;
}
#Override
public Intent getIntent() {
return intent;
}
}
Then I use a dependency injection framework like Dagger or similar like this:
public class MyActivity {
#Inject ActivityLauncher launcher;
public void onCreate(Bundle bundle){
// some code omitted for brevity
findViewById(R.id.goToOtherActivityButton).setOnClick(new OnClickListener(){
Intent intent = new Intent(getContext(), MyOtherActivity.class);
launcher.start(getContext(), intent);
});
}
public ActivityLauncher getLauncher(){
return launcher;
}
}
Testing is then as simple as checkIntentIsValid(activity.geLauncher().getIntent())
This code might give you a good idea
If you are calling Activity1 --- > Activity2
You can send the UserName by this method
Intent intent = new Intent(getBaseContext(), Activity2.class);
intent.putExtra("UserName ", UserName );
startActivity(intent);
To retrive the Extra() in Activity2, you need this code
String UserName = (String) getIntent().getSerializableExtra("UserName ");
Hope this helps
Below Edit for Better Understanding
public class Activity2 extends Activity {
private String UserName;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_2);
UserName= (String) getIntent().getSerializableExtra("UserName");
Log.i(Tag, "UserName: "+ UserName);
}
// you can call this method from click or where ever you want
private void AnyMethod()
{
Intent intent = new Intent(getBaseContext(), Activity3.class);
intent.putExtra("UserName ", UserName );
startActivity(intent);
}
}
#Override
public void onClick(View view) {
startActivity(new Intent(this, AnotherActivity.class));
}
Your code is not correct in every time.
Example:
btn.setOnClickListener(new OnClickListener(
#Override
public void onClick(View view) {
startActivity(new Intent(this, AnotherActivity.class));
}
));
Please replace this = CurrentActivity.this
It looks like:
#Override
public void onClick(View view) {
startActivity(new Intent(CurrentActivity.this, AnotherActivity.class));
}
Make ensure, your Manifest has this code:
<Activity name=".AnotherActivity">
</Activity>
I want to start a new activity in non-Activity class that implements a DialogListener following is my code:
public class FacebookLoginDialog implements DialogListener {
#Override
public void onComplete(Bundle values) {
HomeActivity.showInLog(values.toString());
Intent i1 = new Intent (this, SearchActivity.class);
startActivity(i1);
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
}
I can't start the new activity using intent in onComplete method, please help.
Thanks
This doesn't work because you need a Context in order to start a new activity. You can reorganize your class into something like this:
public class FacebookLoginDialog implements DialogListener {
private final Context context;
public FacebookLoginDialog(Context context) {
this.context = context;
}
#Override
public void onComplete(Bundle values) {
HomeActivity.showInLog(values.toString());
Intent i1 = new Intent (context, SearchActivity.class);
context.startActivity(i1);
}
//Other methods...
}
Then it will work.
Pass context as constructor parameter and then try this
Intent i = new Intent(this, SearchActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
use starActivity from non-activity class:
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "YOUR STRING");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share via...");
context.startActivity(Intent.createChooser(intent, "Share"));
For Easy Usage you can a method for this particular method:
public class Something
{
public static void navigate(Context context, Class<?> nameOfClass)
{
Intent i = new Intent(context, nameOfClass);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
can be called in other class and method everytime by calling this:
Something.navigate(activityName.this, classYourWantTONavigateTo.class);