How do I delete an item through the menu? - java

Below is the code for my submenu buttons and I'm trying to make it delete the note and return to the main list view. The delete option is called "Red" for now.
I copied my delete code from my main activity thinking it would work, but it does not. I'm very new to android coding, so help would be appreciated.
This is how I delete in my Main Activity.java
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
currentNoteId = (int)info.id;
menu.add(0, MENU_DELETE_ID, 0, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == MENU_DELETE_ID) {
Noteitem note = notesList.get(currentNoteId);
datasource.remove(note);
refreshDisplay();
}
return super.onContextItemSelected(item);
}
Here is my code for my NoteEditorActivity.java
Again I'm trying to delete, but I can't seem to figure out how to delete the note from the submenu.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_exit:
EditText et = (EditText)findViewById(R.id.noteText);
if (et.length() > 0) {
saveAndFinish();
}
else
{
finish();
}
case R.id.menu_red:
currentNoteId = (int) MENU_DELETE_ID;
datasource.remove(note);
return true;
default:
return super.onOptionsItemSelected(item);
}

Put break statements in your switch case
switch (item.getItemId())
{
case R.id.action_exit:
EditText et = (EditText)findViewById(R.id.noteText);
if (et.length() > 0){
saveAndFinish();
}else{
finish();
}
//you are missing this!!!
break;
case R.id.menu_red:
datasource.remove(note);
finish();
break;
default:
return super.onOptionsItemSelected(item);
break;
}
Try reading this here also: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

its just weird..you aren't calling notesList.add() method anywhere in your code, so I just think it's empty at all..
you are certainly missing the break statement there, but I guess it is not the issue why your note is not deleted after clicking in the menu item. You are saving your note in the "previous" (in terms of backstack) activity? if so, you might try to just alter the return code for the setActivityResult() call (or add some extras to the intent) and then check for it in your onActivityResult() callback..
because right now everytime you close the activity via back key, the notes is saved (the saveAndFinish() method gets called);
please describe better where you actually do save notes (to DB or so) and where you wanna delete them..I could then provide you with some code snippet probably.

Related

Android, in same activity go back to previous method called

I am coding in Java in Android Studio and I am currently making an Calendar app that save, show, edit events. I had to put some view, like MonthView WeekView and DailyView. At first I made it in a way so all of them were activities and when i want to go back the back pressed button almost done my job. Because of some odds, I turned out to keep only one activity and do the same job with some methods instead of making activities. I have a navigation drawer, so in onItemNavigationClick the user can select which view want. So, my problem is that I cant find a way to act the previous method, like if I go to WeekView and press backButton, get back in Month or in Daily view.
As I see backpressed is to go back an activity, so I think it cant help me. I would apreciate any help.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSchedule:
setAllEvents();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.daysView:
setDaily();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.weekView:
setWeek();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.monthView:
setMonthView();
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.refreshItem:
finish();
startActivity(getIntent());
break;
case R.id.syncItem:
break;
default:
onNavigationItemSelected(item);
}
return true;
}
Example of how my set Methods are working:
private void setMonthView() {
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> daysInMonth = daysInMonthArray();
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this, getApplicationContext());
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
ViewGroup.LayoutParams params = calendarRecyclerView.getLayoutParams();
params.height=1500;
calendarRecyclerView.setLayoutParams(params);
monthListView.setVisibility(View.GONE);
monthYearText.setVisibility(View.VISIBLE);
daysOfWeekDaily.setVisibility(View.GONE);
daysOfWeek.setVisibility(View.VISIBLE);
prevMonth.setVisibility(View.VISIBLE);
nextMonth.setVisibility(View.VISIBLE);
calendarRecyclerView.setVisibility(View.VISIBLE);
nestedScrollView.setVisibility(View.VISIBLE);
}
SOLUTION
Thanks to David Wesser, the code works in the way I want to, here source code of my problem:
public void onMyBackPressed() {
// Pop current view type off the stack
stack.removeFirst();
// Check the previous view type
String previousViewType = stack.peekFirst();
if (previousViewType == null) {
// Nothing to go back to, so finish this Activity
super.onBackPressed();
return;
}
if (previousViewType.equals("daily")) {
setDaily();
} else if (previousViewType.equals("week")) {
setWeek();
} else if (previousViewType.equals("all"))
{
setAllEvents();
}else if (previousViewType.equals("month"))
{
setMonthView();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSchedule:
setAllEvents();
stack.addFirst("all");
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.daysView:
setDaily();
stack.addFirst("daily");
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.weekView:
setWeek();
stack.addFirst("week");
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.monthView:
setMonthView();
stack.addFirst("month");
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.refreshItem:
finish();
startActivity(getIntent());
break;
case R.id.syncItem:
break;
default:
onNavigationItemSelected(item);
}
return true;
}
You can do this by building a stack that represents the type of view you are showing. Whenever the user selects something from the navigation drawer, you call the method to show that view and you push something on the stack (a String or an Integer constant) that represents the kind of view you are showing. Then override onBackPressed() so that instead of the default behaviour (which is to finish the current Activity and return to the previous Activity), you so something like this:
Pop off the last thing from your stack (this represents the currently shown view)
If there is nothing left on the stack, you should call the default behaviour with super.onBackPressed(), which will send the user back to the HOME screen or whatever
Otherwise, examine the topmost thing on the stack (this represents the previously shown view) and use it to call the appropriate method to show the view that it represents. In this case remember not to push a new thing onto the stack because the top item on the stack already represents the view that is being shown.
Code Example:
// Declare the stack as a member variable in the Activity
ArrayDeque<String> stack = new ArrayDeque<String>();
inside your switch statement, something like this for each different view type:
case R.id.daysView:
setDaily();
// push the current view type onto the stack
stack.addFirst("day");
case R.id.weekView:
setWeek();
// push the current view type onto the stack
stack.addFirst("week");
etc...
Now override the behaviour of onBackPressed():
#Override
public void onBackPressed() {
// Pop current view type off the stack
stack.removeFirst();
// Check the previous view type
String previousViewType = stack.peekFirst();
if (previousViewType == null) {
// Nothing to go back to, so finish this Activity
super.onBackPressed();
return;
}
if (previousViewType.equals("day")) {
setDaily();
} else if (previousViewType.equals("week")) {
setWeekly();
} else ... // rest of the view types here
}

I want to link my application back button to android mobile builtin back button

I tried many ways but find out that linking my application to the android back button will be easy for my application but didn't find anyway. If anyone can help me out how can I link so when I press the android mobile back icon my application will also move to back category. Working on Android Studio, API 25.
Try override this method:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
//Your intent
}
return super.onKeyDown(keyCode, event);
}
Or if is your back button from toolbar use this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//your intent
return true;
}
return super.onOptionsItemSelected(item);
}

set RecyclerView invisible

I have a bottom navigation bar which showing the "Setting","Newsfeed" and "Profile". However, when I set to Invisible and it won't display back again. So I created an if statement to check the status of its visibility but it is not working.
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_menu);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.news_icon:
if (mNewsFeedList.getVisibility() == View.INVISIBLE){
mNewsFeedList.setVisibility(View.VISIBLE);
}else{
}
Toast.makeText(newsfeed.this, "news", Toast.LENGTH_LONG).show();
case R.id.profile_icon:
mNewsFeedList.setVisibility(View.INVISIBLE);
Toast.makeText(newsfeed.this, "profile", Toast.LENGTH_LONG).show();
case R.id.setting_icon:
mNewsFeedList.setVisibility(View.INVISIBLE);
}
return false;
}
});`
Another question, is it a good way to set the visibility for navigation? Is there any better way to do it?
Your switch statement is falling through the different cases because you are missing break; statements. What I think you are looking for is:
switch(id) {
case id_1:
//do some work
break;
case id_2:
//do some work
break;
default:
//do other work
}
Java switch statement

Android Up Navigation and Button in Action Bar

I have an action bar that looks like so:
I am using the following to see which button is clicked:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.view_all_trains:
Intent i = new Intent(ToStationActivity.this, MapActivity.class);
startActivityForResult(i, 0);
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
No matter what button you press, (the back or the pin), it goes back to the previous screen and I am not sure why. Any suggestions as to why this may happen?
Put a break statement at the end of each case of the switch!
You need to finish the case at the end using break;, else the control flow continues at the next case.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.view_all_trains:
Intent i = new Intent(ToStationActivity.this, MapActivity.class);
startActivityForResult(i, 0);
break;
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
}
return true;
}

WebView clearHistory() on Webview canGoback() functionality?

I'm trying to use the history as a check to exit the application. The home button reloads the page to google.com, but still retains page history even after I call .clearHistory().
Here is the code for the Menu handling / selections:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.Home:
mWebview.loadUrl("http://google.com");
mWebview.clearHistory();
return true;
case R.id.About:
Toast.makeText(this, "TEXT", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Here is the code for the Exit function:
#Override
public void onBackPressed() {
if (mWebview.canGoBack()) {
mWebview.goBack();
}
else {
super.onBackPressed();
}
}
According to this post you need to call clearHistory when the page finished loading:
It appears that the history clears everything before the current page
so if your browser is at page "A", you clear history and navigate to
page "B" your history will be "A" "B", not just "B", but if you clear
history when "B" finishes loading you will have only "B"
So instead of calling clearHistory right after loadUrl, you should envoke it from onPageFinished or onProcessChanged.

Categories

Resources