onOptionsItemSelected(MenuItem item) strange behavior - java

I've created a menu with a intents to access different activities, but I have a strange behavior, it always goes through all the cases of the switch statement after the statement selected , I've reviewed the value of the variable item and is correct, any ideas what could be wrong?
the snippet of code that represents the menu is:
public static final int wiifidi = 0;
public static final int cuentaint = 1;
public static final int cajerosint = 2;
public static final int indicadoresint = 3;
public static final int promoint = 5;
public static final int contactoint = 4;
....
....
....
#Override
//add the items to the menu on the class
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0,wiifidi, 0, R.string.menu_wifi);
menu.add(0,cuentaint, 0, R.string.menu_cuenta);
menu.add(0,cajerosint,0,R.string.menu_cajeros);
menu.add(0,indicadoresint,0,R.string.menu_indicadores);
menu.add(0,contactoint,0,R.string.menu_contacto);
menu.add(0,promoint,0,R.string.menu_promo);
return result;
}
#Override
//handle everything that happens when an item of menu is selected
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(getApplicationContext(), "el item es " +item.getItemId(), Toast.LENGTH_LONG).show();
switch (item.getItemId()) {
case wiifidi:
wifistatus();
case cuentaint:{
consulta();
}
case cajerosint:{
cajero();
}
case indicadoresint:{
indicador();
}
case contactoint:{
contacto();
}
case promoint:{
promocion();
}
}
return super.onOptionsItemSelected(item);
}

Remember to break out of your switches.
switch (item.getItemId())
{
case wiifidi:
wifistatus();
break;
case cuentaint:
consulta();
break;
case cajerosint:
cajero();
break;
case indicadoresint:
indicador();
break;
case contactoint:
contacto();
break;
case promoint:
promocion();
break;
}

Specify break
case wiifidi:
wifistatus();
break;

Related

TabLayout fragments are instantiated as the same when debugger is not connected

I have a TabLayout that uses a custom adaptor (TabPagerAdapter.java), it's initialised with this function (I previously had the problem that things didn't update when replaced so it removes everything before initializing):
public boolean setPagerViewContents(int mode, ArrayList<String> titles) {
try {
mTabLayout.removeAllTabs();
mViewPager.setAdapter(null);
mViewPager.removeAllViews();
for (int i = 0; i < titles.size(); i++) {
mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(i)));
}
mAdapter = new TabPagerAdapter(getSupportFragmentManager(), titles.size(), mode);
mViewPager.setAdapter(mAdapter);
mViewPager.invalidate();
return true;
} catch (Exception e) {
mErrorReporter.reportError(e);
return false;
}
}
Custom adapter (TabPageAdapter.java):
public class TabPagerAdapter extends FragmentStatePagerAdapter {
int mTabCount;
int mLayoutType;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs, int layoutType) {
super(fm);
this.mTabCount = numberOfTabs;
this.mLayoutType = layoutType;
}
#Override
public Fragment getItem(int position) {
switch (mLayoutType) {
case 0:
switch (position) {
case 0:
return new Fragment15();
case 1:
return new Fragment1();
default:
return null;
}
case 1:
switch (position) {
case 0:
return new Fragment3();
case 1:
return new Fragment2();
default:
return null;
}
default:
return null;
}
}
#Override
public int getCount() {
return mTabCount;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
When the app starts the function setPagerViewContents (with the right mode and titles) is called, after that mViewPager.setCurrentItem(number) is called to display the right tab. But now the fragment displayed in mViewPager is correct but when clicking on a tab title the fragment is the same displayed at start (the one with the index number, not the one that should have been displayed), when tapping the first (number) tab again and then again to some other tab (not number) the shown tab is correct.
The most annoying thing here is that it's NOT consistent, it sometimes happens, sometimes doesn't and it doesn't happen when the debugger is attached so I can't debug it properly. If some other code is needed please do tell, I'll update this post as quick as possible because I'd really love to see this solved, for my own sanity and for the happiness of my few users.
Change your following method:
public boolean setPagerViewContents(int mode, ArrayList<String> titles) {
try {
mAdapter = new TabPagerAdapter(getSupportFragmentManager(), titles.size(), mode);
mViewPager.setAdapter(mAdapter);
mTabLayout.setupWithViewPager(mViewPager);
return true;
} catch (Exception e) {
mErrorReporter.reportError(e);
return false;
}
}
and set text on tabs in TabPagerAdapter by overriding following method:
#Override
public CharSequence getPageTitle(int position) {
return context.getString(tabTitles[position]);
}

How can I implement a string stack with a switch statement?

I would like to implement my StringStack in a switch statement how can i make this work in java. it sais i cant push() and argument with a char value. What is the best way around this for my validation method?
package xmlvalidator;
public class BasicXmlValidator implements XmlValidator {
#Override
public String[] validate(String xmlDocument) {
// TODO Auto-generated method stub
int charIndex = 0;
char currentCharacter;
String characterString;
while (charIndex < xmlDocument.length()) {
currentCharacter = xmlDocument.charAt(charIndex);
characterString = Character.toString(currentCharacter);
switch (currentCharacter) {
case '(': StringStack.push(currentCharacter);
break;
case '[': StringStack.push(currentCharacter);
break;
case '{': StringStack.push(currentCharacter);
break;
case ')': StringStack.push(currentCharacter);
break;
case ']': StringStack.push(currentCharacter);
break;
case '}': StringStack.push(currentCharacter);
break;
}
}
return null;
}
}
package xmlvalidator;
import static java.lang.System.*;
public class BasicStringStack implements StringStack {
public int count; // Number of Items in the array
public String[] stackItems; // The array that holds the stack items
public BasicStringStack(int initialSize) {
count = 0;
stackItems = new String[initialSize];
}
#Override
public void push(String item) {
// TODO Auto-generated method stub
if (count == stackItems.length) {
int newLength = (stackItems.length + 1);
String[] tempArray = new String[newLength];
arraycopy(stackItems, 0, tempArray, 0, stackItems.length);
stackItems = tempArray;
}
stackItems[count++] = item;
}
#Override
public String pop() {
if (count == 0) {
return null;
} else {
return stackItems[--count];
}
}
#Override
public String peek(int position) {
if ((position > count - 1) || (position < 0)) {
return null; // outside Bounds
} else {
return stackItems[count - position - 1];
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
}
You have the current char stored in a string using characterString = Character.toString(currentCharacter); just use it to push into stack.
StringStack.push(currentCharacter);
change to
StringStack.push(currentString);
Your problem is exactly as Java describes it to you. You pass a char to a method that expects String. The best fix would be
Stringstack.push(characterString);
Aside: because switch lets you fall through, you can rewrite it as
switch (currentCharacter) {
case '(':
case '[':
case '{':
case ')':
case ']':
case '}':
StringStack.push(characterString);
break;
}
Further aside: I did not address other potential problems in the code, but sought only to address the question asked.

Android drag and drop on dynamically created views

could really do with some help.
I have a random number of buttons being created on the fly and each button is setOnTouchListener, which looks to be working fine. The buttons are added to Linearlayout (Top) and there is another empty Linearlayout (Bottom).
I want to be able to do the following:
Drag & Drop buttons between Linearlayout (Top) & Linearlayout (Bottom)
public class GetString extends Activity{
myDragEventListener mDragListen = new myDragEventListener();
public void getString(Context context, String[] temp, int no, LinearLayout words1, LinearLayout words2) {
Button bt;
int i = 0;
for (i = 0; i < no; i++) {
bt = new Button(context);
bt.setId(i);
bt.setText(temp[i]);
bt.setOnTouchListener(new MyTouchListener());
words1.addView(bt);
bt.setOnDragListener(mDragListen);
}
}
protected class myDragEventListener implements View.OnDragListener {
public boolean onDrag(View v, DragEvent event) {
// Defines a variable to store the action type for the incoming event
final int action = event.getAction();
// Handles each of the expected events
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
return false;
case DragEvent.ACTION_DRAG_ENTERED:
v.invalidate();
return true;
case DragEvent.ACTION_DRAG_LOCATION:
return true;
case DragEvent.ACTION_DRAG_EXITED:
v.invalidate();
return true;
case DragEvent.ACTION_DROP:
return true;
case DragEvent.ACTION_DRAG_ENDED:
return true;
// An unknown action type was received.
default:
Log.e("DragDrop Example", "Unknown action type received by OnDragListener.");
break;
}
return false;
}
}
public class MyTouchListener implements View.OnTouchListener {
#Override
public boolean onTouch(View v, MotionEvent arg1) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadow = new View.DragShadowBuilder(v);
v.startDrag(data, shadow, null, 0);
return false;
}
}
}

Switch statement just returning the last case

Switch statment fix:
The switch statement is only returning the last case i.e case 4, "#0R0dfdf0FF". how can i fix this so the text view shows the the one clicked in the dialogue box?
I'm a total newbie so yes help would really be appreciated.
public class NoteEdit extends Activity {
public EditText mTitleText;
public EditText mBodyText;
public EditText mColor;
private NotesDbAdapter mDbHelper;
private static final int DIALOG_ALERT = 10;
Long mRowId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
setTitle(R.string.done);
mTitleText = (EditText) findViewById(R.id.editTitle);
mBodyText = (EditText) findViewById(R.id.editNote);
mColor = (EditText) findViewById(R.id.editColor);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
setupActionBar();
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
setResult(RESULT_OK);
finish();
}
return super.onOptionsItemSelected(item);
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
mColor.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_COLOR)));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
String color = mColor.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, color);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, color);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case R.id.add:
showDialog(DIALOG_ALERT);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
// Create out AlterDialog
android.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);
final String[] colors = {"Blue", "Green", "Yellow", "Red", "Purple"};
builder.setTitle(R.string.body);
builder.setItems(colors, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which){
case 0:
mColor.setText("#000000");
case 1:
mColor.setText("#0000FF");
case 2:
mColor.setText("#0R00FF");
case 3:
mColor.setText("#0R00dsdFF");
case 4:
mColor.setText("#0R0dfdf0FF");
default:
break;
}
} });
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
}
You are missing break; at the end of the switch branches.
Fall Through.
You have to add the break.
case 0:
mColor.setText("#000000");
break;
You can find that in docs
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
You need a break when you don't have a return otherwise it causes fall through
You need the break; after all cases except for the last one or else it'll fall through case by case
switch (which){
case 0:
mColor.setText("#000000");
break;
case 1:
mColor.setText("#0000FF");
break;
case 2:
mColor.setText("#0R00FF");
break;
case 3:
mColor.setText("#0R00dsdFF");
break;
case 4:
mColor.setText("#0R0dfdf0FF");
default:
break;
}

Android: how to create Switch case from this?

public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(CategoriesTab.this);
adb.setTitle("Selected Category");
adb.setMessage("Selected Item is = "+lv1.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
This at the moment displays an alertbox when an item from listview is clicked. I want to convert the alertbox to load a specific xml for each choices clicked. How can i do this?
thanks for your help.
switch(position) {
case 0:
setContentView(R.layout.xml0);
break;
case 1:
setContentView(R.layout.xml1);
break;
default:
setContentView(R.layout.default);
break;
}
i hope this will do the job!
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.:
break;
case R.id.:
break;
default:
break;
}
}
switch(position) {
case 0:
...
break;
case 1:
...
break;
default:
...
}
Did you mean that?
You can do this:
#Override
protected Dialog onCreateDialog(int id) {
String messageDialog;
String valueOK;
String valueCancel;
String titleDialog;
switch (id) {
case id:
titleDialog = itemTitle;
messageDialog = itemDescription
valueOK = "OK";
return new AlertDialog.Builder(HomeView.this).setTitle(titleDialog).setPositiveButton(valueOK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.d(this.getClass().getName(), "AlertItem");
}
}).setMessage(messageDialog).create();
and then call to
showDialog(numbreOfItem);

Categories