I want to open a new activity, Make_a_contact, from my popup menu. The problem I'm sure is related just to the code below, because when I uncomment the code below - Toast.makeText etc...(and remove the code I want fixed) it works fine.
Thanks for any help!
public void Show_Settings(View v) {
//this is the settings button, whose onclick is identified in menu_thisisatest.xml
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_thisisatest, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
Intent intent = new Intent(this, Make_a_contact.class);
return true;
// #Override
// public boolean onMenuItemClick(MenuItem item) {
// Toast.makeText(getApplicationContext(),item.toString(),Toast.LENGTH_SHORT).show();
// return true;
// }
});
popup.show();
}
You need to start your new Activity after generating your intent. Try calling
startActivity(intent);
And, of course, you need to include that code in the onMenuItemClick() method, that is currently commented out in your code, i.e.
#Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(this, Make_a_contact.class);
startActivity(intent);
return true;
}
Regarding the comment to #Benjamin Scharbau's answer, when you create intent with new Intent(this, Make_a_contact.class), this is a reference to the anonymous instance of PopupMenu.OnMenuItemClickListener class which isn't inherited from Context (this is the reason for the error). You should use a context in the Intent's constructor, so use the reference to the calling (foreground) Activity, e.g.
Intent intent = new Intent(ClassNameOfCallingActivity.this, Make_a_contact.class)
and pass the intent to the startActivity() method.
Related
Using android studio with java, I am using a dialog class called ExampleDialog.java ran from MainActivity.java. I have to pass one int and one String to MainActivity.java.
I tried to use intent to pass the values, but there is a problem when there are consecutive return dialog; and startActivity(intent);.
I tried to remove first the return dialog; and keep the startActivity(intent); but it does not work well because there are problems with the dialog.
I also tried the opposite by removing the startActivity(intent); and keeping the return dialog;. In this case, I think that the int and the String are not passed to MainActivity.java, so this does not work too.
ExampleDialog.java:
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//code
Dialog dialog = builder.create();Intent intent = new Intent(getContext(), MainActivity.class);
intent.putExtra("EXTRA_NAME", name);
intent.putExtra("EXTRA_NUMBER", number);
startActivity(intent);
return dialog ;
}
I have a MainActivity which has a navigation drawer and a framelayout container to show different fragments. On my navigation drawer there is an option which launches another activity(lockpattern activity) to show a lockpattern (had to use activity cause the library doesn't support fragments yet. Link to Library).Once the user has set up his pattern or canceled the procedure,i want the lockpattern activity to get destroyed and show the previous mainActivity and the same fragment what was there in the container before the lockpattern activity was launched.The problem im facing is that once the backbutton is pressed or even if i call the finish() function,it doesn't show the previous activity(ie Main activity) but instead relaunches the lockpattern activity.i have even tried super.onBackPressed(); and it doesn't seem to work.Any help or ideas to get around this is gratefully accepted.
Code of Lockpattern
public class Create_Pattern extends Activity {
private static final int REQ_CREATE_PATTERN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// This is your preferred flag
LockPatternView.MATRIX_WIDTH = 4;
Intent intent = new Intent(LockPatternActivity.ACTION_CREATE_PATTERN,
null, getBaseContext(), LockPatternActivity.class);
startActivityForResult(intent, REQ_CREATE_PATTERN);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQ_CREATE_PATTERN: {
if (resultCode == RESULT_OK) {
char[] pattern = data
.getCharArrayExtra(LockPatternActivity.EXTRA_PATTERN);
DataBaseHandler handler = new DataBaseHandler(this);
handler.open();
String PatternToWrite = new String(pattern);
handler.createPattern(PatternToWrite);
handler.close();
Log.d("DEBUG", new String(pattern));
Toast.makeText(getApplicationContext(), "Pattern Recorded",
Toast.LENGTH_LONG).show();
finish();
}
if (resultCode == RESULT_CANCELED) {
finish();
}
break;
}// REQ_CREATE_PATTERN
}
}
}
You should create a new Intent that points to the Activity you want to navigate to next, start that activity by calling startActivity(intent). Then you can call finish() to destroy the current Activity.
Another approach, (which I have not tried yet) is to create an 'up button' hierarchy and manually call NavUtils.navigateUpFromSameTask(this);
Documentation:
http://developer.android.com/training/implementing-navigation/ancestral.html
http://developer.android.com/reference/android/support/v4/app/NavUtils.html
Basically I want to do an if statement like below, but I don't know how.
if (Android_Classes_Left_Open){
Intent a = new Intent(SplashScreen.this, 2ndtoTopElement.class);
startActivity(a);
} else {
Intent a = new Intent(SplashScreen.this, Other.class);
startActivity(a);
}
My SplashScreen code so far:
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, First.class);
startActivity(i);
finish();
}
}, 3000);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
}
The purpose of this is, if the user moves the application into the background they are then returned to their most recently opened activity rather than starting the application from scratch each time. How can I achieve this?
your solution is that whenever you entered in any new activity....
1.) You have to save the name of this activity in shared preferance(on same key) you have to perform this things in onResume() of every activity or your BaseActivity.
2.) At the every time of splash screen you have to check the name of this activity and pass it in your intent.
so you get the last open activity each time after your splash screen done.
I've created a common re-usable class for the company I work for to create some common interface elements.
The class, takes in a single parameter as in the construct: an application context.
one of the methods, ContentClickableRowWithIcon allows you to pass in an intent to be used as the click action.
heres the full method declaration:
public LinearLayout ContentClickableRowWithIcon(Drawable icon, String title, Intent i, final Boolean chooser)
that last attribute there is used in the onClickEvent to determine whether to invoke a Chooser or just go right into the intent.
public LinearLayout ContentClickableRowWithIcon(Drawable icon, String title, Intent i, final Boolean chooser) {
LinearLayout ll = new LinearLayout(mContext);
// .. LinerLayout construction, has nothing to do with the action
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this is apparently getting ignored... (ps: i've tried i.setFlags as well)
final Intent intent = i;
ll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(chooser)
mContext.startActivity(Intent.createChooser(intent, "Complete With...")); // crashes here with: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
else
mContext.startActivity(intent); // this works fine
}
});
return ll;
}
As mentioned in the comments, anytime I dont provide the ability to use a chooser, everything works fine (everything in this list gets a new activity flag, im well aware of this and will cleanup when this issue is figured out)
The moment I do, throws the exception:
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
I've run out of ideas...
/// EDIT:: Worth noting, on debug, the flags attribute in the Intent is set to 268435456 with addFlags and 268435456 with setFlags, when it reaches the time to use the intent in the onClick action
Problem has been fixed, I think this is simply the case of an "order of operation" scenario
heres what allowed this thing to work:
ll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(chooser) {
Intent intent = Intent.createChooser(i, "Complete With");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
} else
mContext.startActivity(i);
}
});
also added a "final" modifier to the parameter in the method declaration
public LinearLayout ContentClickableRowWithIcon(Drawable icon, String title, final Intent i, final Boolean chooser)
Actually your exception mean that you are using Not Activity Context. it could be called from Application context. Check that you are in Activity context since this is not a service
I fixed it adding the flag to the Chooser Intent
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here")
.putExtra(android.content.Intent.EXTRA_TEXT, url)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(Intent.createChooser(sharingIntent, "Share with").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
Say I'm on my main activity and I start a new activity
MainActivity > NewActivity
And from NewActivity I press the back key
MainActivity < NewActivity
I want MainActivity to do something if it's being displayed after NewActivity is closed, but not when MainActivity is run normally, such as when first running the application. Does anyone know if this is possible?
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "back button pressed");
}
return super.onKeyDown(keyCode, event);
}
#Update. If you want to be notified when NewActivity is finished, you have to start it by startActivityForResult(Intent, requestCode). Then, you must override onActivityResult() on MainActivity. Check the requestcode parameter here, if the return code equals the submit code (when you start childActivity), put some code to do your business.
int MYCODE=1000;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Result OK.d.
if (requestCode == MYCODE) {
// do something good
}
}
I try the below method to detect the back button pressed on the action bar in activity by the first method and the second one is used to detecting the mobile hardware button back or kill activity button.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
setResult(RESULT_CANCELED);
super.onBackPressed();
}
You can override onBackPressed() method in NewActivity which will detect when back button is pressed. And then to inform the MainActivity about it, you can send a boolean flag in a bundle so that MainActivity detects that its opening after NewActivity.
In NewActivity:
#Override
public void onBackPressed() {
boolean fromNewActivity=true;
Intent mainIntent = new Intent(view.getContext(), MainActivity.class);
Bundle bundleObj = new Bundle();
bundleObj.putString("fromNewActivity", Boolean.toString(fromNewActivity));
mainIntent.putExtras(bundleObj);
startActivityForResult(mainIntent, 0);
}
In MainActivity in onCreate() method :
Bundle extras = getIntent().getExtras();
boolean fromNewActivity =Boolean.parseBoolean( extras.getString("fromNewActivity"));
Now you can check if the MainActivity is opened after NewActivity or not.
A couple of ideas:
You can just set a flag in MainActivity when it fires up NewActivity.
You can call startActivityForResult from MainActivity and arrange for NewActivity to set a result, which you will receive in MainActivity.onActivityResult() when NewActivity finishes.
When you start NewActivity you need to use startActivityForResult and use a valid requestId. Such requestId will be passed back to you to onActivityResult once NewActivity finishes.