I am currently working on an Android Studio project, and I've stumbled into an issue, no matter which option I pick in the menu, it changes activity to all of them in a row, and then crashes.
Here's my home page menu functions:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
menu.removeItem(R.id.HomePage);
if (sp.getLong("User_Id", -1) != -1) {
menu.removeItem(R.id.Login);
menu.removeItem(R.id.SignUp);
}
else {
menu.removeItem(R.id.LogOut);
}
if (sp.contains("User_Id")){
if (!database.userDao().GetUserById(sp.getLong("User_Id", -1)).getUserEmail().equals(R.string.admin_email))
menu.removeItem(R.id.UserList);
}
else
menu.removeItem(R.id.UserList);
return true;
}
#SuppressLint("NonConstantResourceId")
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.SignUp: {
startActivity(new Intent(MainActivity.this, RegisterActivity.class));
}
case R.id.Login: {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
case R.id.UserList: {
startActivity(new Intent(MainActivity.this, UserActivity.class));
}
case R.id.LogOut:{
builder.setMessage(R.string.logout_dialog_message).setTitle(R.string.logout_dialog_title).setCancelable(true).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
editor.clear();
editor.commit();
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
case R.id.About: {
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_about_dialog);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
dialog.getWindow().getAttributes().windowAnimations = R.style.animation;
ImageView image = dialog.findViewById(R.id.IVLogo);
TextView text = dialog.findViewById(R.id.TVText);
image.setBackground(getDrawable(R.drawable.logo));
text.setText("About us: We are regel2, the new best second hand app. In this app, you are able to buy and sell any product that you want, for any price that you want, all inside 1 app.");
dialog.show();
}
}
return super.onOptionsItemSelected(item);
}
Note: It opens even deleted menu items (Aka menu.removeItem(___)) and it doesn't happen when I click on the about item, which may act differently because it's a dialog.
You need to put
break;
as the last statement of every case block, otherwise execution will continue to the end.
Related
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homeactivity);
list(getIntent().getExtras().getString("JSON_Object"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.items, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.changepwd:
// Intent myIntent = new Intent(HomeActivity.this, Change_Password_Activity.class);
// this.startActivity(myIntent);
startActivity(new Intent("com.example.aishwarya.registerlogin.change_password_activity"));
Toast.makeText(this, "You selected change pwd", Toast.LENGTH_SHORT).show();
break;
case R.id.setuname:
Toast.makeText(getApplicationContext(), "You selected set username", Toast.LENGTH_SHORT).show();
break;
case R.id.setdp:
Toast.makeText(getApplicationContext(), "You selected set profile picture", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
You should use the code that you have commented:
Intent myIntent = new Intent(HomeActivity.this, Change_Password_Activity.class);
startActivity(myIntent);
Make sure that the name of the activity you want to inicialize has the name "Change_Password_Activity"
try this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id){
case R.id.changepwd:
// Intent myIntent = new Intent(HomeActivity.this, Change_Password_Activity.class);
// this.startActivity(myIntent);
startActivity(new Intent("com.example.aishwarya.registerlogin.change_password_activity"));
Toast.makeText(this, "You selected change pwd", Toast.LENGTH_SHORT).show();
break;
case R.id.setuname:
Toast.makeText(getApplicationContext(), "You selected set username", Toast.LENGTH_SHORT).show();
break;
case R.id.setdp:
Toast.makeText(getApplicationContext(), "You selected set profile picture", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
I'm trying to set Context menu to onBackPressedButton like "Are you sure to quit?"
Here I override onBackPressed:
I don't know how to call menu. What should I register here?
#Override
public void onBackPressed() {
registerForContextMenu();
return;
}
or what view should I attach?
#Override
public void onBackPressed() {
this.openContextMenu();
return;
}
Should I create viewList to it?
I've overridden onCreateContextMenu:
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
menu.add(0,YES,0,"Yes");
menu.add(0,NO,0,"No");
}
I've also overridden and onContextItemSelected:
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case YES:
finish();
break;
case NO:
break;
}
return super.onContextItemSelected(item);
}
How must I do it?
Just call onBackPressed() method in your class. Find a sample code below.
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
LoginActivity.super.onBackPressed();
finish();
}
}).create().show();
}
here is the code. When I long click on an item and dont drag my finger away from it, the menu still pops up, but it also activates my onClick listener. I have no idea why. I have tried looking for solutions online, and I only found something that told me to check the return statement. I am returning True, so I do not know what else to do.
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(AddClaim.this, "Clicked "+list.get(position), Toast.LENGTH_SHORT).show();
//adapter expenses
setContentView(R.layout.add_expense);
ListView expView = (ListView) findViewById(R.id.ExpenseListView);
Collection<Expense> expenses = list.get(position).getExpenses();
final ArrayList<Expense> expense = new ArrayList<Expense>(expenses);
final ArrayAdapter<Expense> expAdap = new ArrayAdapter<Expense>(AddClaim.this, android.R.layout.simple_list_item_1, expense);
expView.setAdapter(expAdap);
}
});
//LONG CLICK FUNCTIONS
listView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final int finalPosition = position;
PopupMenu popup = new PopupMenu(AddClaim.this, view);
popup.getMenuInflater().inflate(R.menu.add_claim, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
//DELETE button check.
if (item.getTitle().equals("Delete")){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(finalPosition).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(finalPosition);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}//end of delete button check
//START of ADD EXPENSE check
if (item.getTitle().equals("Add Expense")){
Intent intent = new Intent(AddClaim.this, ExpenseAdd.class);
intent.putExtra("somename", finalPosition);
startActivity(intent);
}
//end of add expense check
return true;
}
});
popup.show();
return false;
}
});
}
Look carefully at your code,and count your braces but read my comments
listView.setOnItemLongClickListener(new OnItemLongClickListener(){ //function starts here
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) { // longclick starts here
final int finalPosition = position;
PopupMenu popup = new PopupMenu(AddClaim.this, view); // your menu code starts here
popup.getMenuInflater().inflate(R.menu.add_claim, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
//DELETE button check.
if (item.getTitle().equals("Delete")){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(finalPosition).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(finalPosition);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}//end of delete button check
//START of ADD EXPENSE check
if (item.getTitle().equals("Add Expense")){
Intent intent = new Intent(AddClaim.this, ExpenseAdd.class);
intent.putExtra("somename", finalPosition);
startActivity(intent);
}
//end of add expense check
return true; // you only return true if onmenu item is clicked.. which is too late
}
});
popup.show(); // and your menu code ends here, because this is where it is shown..
return false; // you are returning false.. this is {star line}
} //longclick ends here
}); //function ends here
}
{start line} should return true
I have a problem, which is also discussed here:
onBackPressed never gets called
I'm trying to cancel a CountDownTimer when pressing the native back button from an android phone. So I would like to overrite the onBackPressed method, to cancel the timer and return to another activity, but only once. (to return to the main activity, like a home button).
This is a part of the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE){
ImageView und1=(ImageView)findViewById(R.id.undita1);
ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) und1.getLayoutParams();
params.height=150;
und1.setLayoutParams(params);
ImageView und2=(ImageView)findViewById(R.id.undita2);
ViewGroup.LayoutParams params2 = (ViewGroup.LayoutParams) und2.getLayoutParams();
params2.height=150;
und2.setLayoutParams(params2);
ImageView und3=(ImageView)findViewById(R.id.undita3);
ViewGroup.LayoutParams params3 = (ViewGroup.LayoutParams) und3.getLayoutParams();
params3.height=150;
und3.setLayoutParams(params3);
}
mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setProgress(0);
mCountDownTimer=new CountDownTimer(90000,1000) {
int i=0;
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i + millisUntilFinished);
i++;
mProgressBar.setProgress(i); }
#Override
public void onFinish() {
i++;
mProgressBar.setProgress(i);
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
}
};
mCountDownTimer.start();
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Bundle b;
b = getIntent().getExtras();
nivel= b.getInt("level");
TextView niv=(TextView) findViewById(R.id.Nivel);
niv.setText("Level: "+ nivel);
generare_3_diferente(nivel);}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
mCountDownTimer.cancel();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
#Override
public void onBackPressed(){
mCountDownTimer.cancel();
Intent in = new Intent(this, MyActivity2.class);
startActivity(in);
super.onBackPressed();
}
}
the onBackPressed should be in the main activity class
Also try to specify the parent and child activities in the manifest file of the app e.g
android:parentActivityName
and try to use something like this and rebuild your App
#Override
public void onBackPressed() {
super.onBackPressed();
i = new Intent(CurrentActivity.this, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
if it still doesn't work try to make a new application and import your files
I want to show a alert dialog box to the user when the back button is pressed..For example :Are you sure want to exit ?.I am not having a problem in creating a alert dialog box..I am having a problem in where to call this dialog box method().
This is my HomeScreen.java
public class HomeScreen extends TabActivity {
ConferenceOpenHelper helper_ob;
Cursor cursorHome;
ProfileEditScreen profileEditScreen;
ConferenceAdapter adapter;
EcMeeting meeting;
final Context context = this;
public static int HOMETEMP = 1;// Constant for Deleting the last created id
// in edit profile screen (Cancel)
public static String HOME = "home";// constant for updating status column
public static String CUSTOM_DIALER = "custom";
public static String TEMPLATE = "template";// constant for updating status // column
public static TabHost tabHost;
public static final int QUICK_START = 1;// Constant for menu options
public static final int TEMPLATE_SCREEN = 2;// Constant for menu options
public static final int USER_GUIDE = 3;// Constant for menu options
public static final int QUICK_CALL = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
Resources ressources = getResources();
tabHost = getTabHost();
// Android tab
Intent photo = new Intent().setClass(this,EcMeeting.class);
TabSpec tabSpecphoto = tabHost
.newTabSpec("Calendar")
.setIndicator("Calendar", ressources.getDrawable(R.drawable.calendartab))
.setContent(photo);
// Apple tab
Intent intentApple = new Intent().setClass(this,CallListScreen.class);
TabSpec tabSpecApple = tabHost
.newTabSpec("Calls")
.setIndicator("Calls", ressources.getDrawable(R.drawable.ic_action_device_access_call))
.setContent(intentApple);
// Windows tab
Intent intentWindows = new Intent().setClass(this,UserSettingActivity.class);
TabSpec tabSpecWindows = tabHost
.newTabSpec("Settings")
.setIndicator("Settings", ressources.getDrawable(R.drawable.ic_action_setting))
.setContent(intentWindows);
// add all tabs
tabHost.addTab(tabSpecphoto);
tabHost.addTab(tabSpecApple);
tabHost.addTab(tabSpecWindows);
//set Windows tab as default (zero based)
/*tabHost.setCurrentTab(0);*/
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#d3d3d3"));
}
tabHost.getTabWidget().setCurrentTab(0);
/*tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#C35817"));*/
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, QUICK_START, 0, "Quick Start").setIcon(R.drawable.ic_menu_add_icon);
menu.add(0, USER_GUIDE, 0, "User Guide").setIcon(R.drawable.ic_menu_guide_icon);
return true;
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case QUICK_START:
startActivity(new Intent(this, ConfDialerScreen.class));
break;
case USER_GUIDE:
startActivity(new Intent(this, UserGuideScreen.class));
break;
}
return true;
}
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#8A4117"));
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#C35817"));
}
}
This is the method() to create alert dialog
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
Now ,I really did not know where to call this method.Could someone give any Idea?
when user press the back button I want to show the alert Dialog.
Try below code:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialogOnBackPress();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void dialogOnBackPress() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
Use this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert Message:");
builder.setMessage("Do you want to save this image to your file??");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// do your stuff
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
you can this code modify acc. to req.
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
dialog.dismiss();
}
return true;
}
});
do not call super.onBackPressed(); in onBackPressed
Else you can simply add onBackPressed() in activity_main.xml(tab.xml) as
android:onClick="onBackPressed"
mention it in your button properties