Android: Count number of cases in switch statement, know when last case - android

I am busy working on an app with multiple switch statement that each have a different number of cases.
switch(variable){
case: 0
//do something
case: 1
//do something
case: 3
//do something
I can iterate through the cases by using variable = variable +1. That works fine. My problem is being able to tell when the last case in the switch statement has been reached so that I can perform a different action.
How do I know when the count is at the last case? What is the code for that?
I appreciate your time.

You can use default case for your problem.
switch(variable){
case: 0
//do something
break;
case: 1
//do something
break;
case: 3
//do something
break;
default:
// Here you can run your different action
break;
}
You have to also define the max value for your variable so that when your variable value reaches to that max value it stops incrementing the variable value.

I think you are working inside a method or cycle
In that case you can restart the variable when it reaches the last value inside your switch
.
.
.
switch(variable){
case 0:
//do something
case 1:
//do something
case 2: //this is the last
.
.
.
//do something
.
.
.
variable = 0;
}//End of switch
.
.
.
[EDIT]
You can restart the variable in the last case of your switch.

Related

View objects id

I have several objects in an activity and I would like to check their id before I perform any actions on them. However I'm not sure how to go about it, I tried :
if (v.getId().contains("empty")){
but that gives an error and then I tried
if (v.getId() == "[attr^=empty]"){
and that is also wrong. To be honest I am aware that both of these don't use proper assignments and so on but I'm really lost on how to check whether an id contains a certain substring.... I would appreciate it if someone could help
PS: v is a View object
v.getId() returns an integer. In order to check id before doing something, I'd recommend something like:
switch (v.getId()){
case R.id.ViewElement1:
//do something here
break;
case R.id.ViewElement2:
//do something here
break;
case R.id.ViewElement3:
//do something here
break;
}
What this code does is that it gets the Id of your View then compares it through a switch-case block. If the id taken from v.getId(), the code in the case block executes. The break; is important, otherwise, the code in the cases below the one executed will also run. You can also do this for an if-else if that fits your style more.
If you want to fetch the id as a string, you can try:
String ResourceIdAsString = v.getResources().getResourceName(v.getId());
and then you can do your if contains operations on the String object.
I am not entirely sure what you are trying to achieve. So there's some overview of how id works.
First you have to id all of your views in xml like:
<TextView
android:height="wrap_content"
android:weight="match_parent"
android:id="#+/myTextView" />
Then in your JAVA code use a switch case like:
switch(view.getId()){
case R.id.myTextView1:
break;
}
If you have some views that do same thing you can use them like:
switch(view.getId()){
case R.id.myTextView1:
case R.id.myTextView2:
case R.id.myTextView3:
case R.id.myTextView4:
perfomeSomeAction();
break;
}

Make an array of methods to call

I have some classes on my code and based on the click of the listview i want to run the selected class. What I mean is that if a user clicks on position 0 I want to run method GoToTown().
I have more than 40 methods so if I do it with if / elseif it would be really bad. I have a custom adapter for the listview so probably I could use it somehow?
Is there some way I could pass an array to do it?
Instead of using 40 different methods, use only 1 (the one which should get the listview result and call one of the 40 methods). And then you should have a switch inside it:
// "number" is the number if the item clicked in the list
switch (number) {
case 0: // First item was clicked, counting starts from 0
// Put some code here
break;
case 1: // Second item...
// Other code
break;
// Etc.
default: // You did not define a "case" for a number, default gets executed
// Code here
}

What do the cases and methods mean ? [duplicate]

This question already has answers here:
openSearch() in Android beginners app not defined
(3 answers)
Closed 9 years ago.
So I'm basically following this tutorial to learn the basics of programming, and at respond to action buttons they have this coding:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
but they dont talk about the case part at all, and now I don't understand what to do. I think (?) i need to create a method for the opensearch() and opensettings(), but what do i put in here, and what does the case part mean?
thanks for your help!
The switch | case structure is a conditional statement. The switch receives a variable that'll be compared to one or several values. I usually think of it as an elegant way of writing if statements.
Each case is a comparison to be made to the value stored in the variable provided to the switch. In this case, R.id.action_search and R.id.action_settings are both ID's (string or number. In this case I don't know which, since I haven't used the tutorial) that must be compared to the value of item.getItemId().
The default is the action that will be performed if none of the previous case statements are met.
So, depending on the value of item.getItemId(), possible actions are either the execution of openSearch() or openSettings() (both ending with return true). But, if neither condition is met, then no methods will be executed and the value returned will be super.onOptionsItemSelected(item)
So, if you cannot find, in that tutorial, the code for those two methods, then it's most likely an abstraction thrown at you to illustrate what actions would take place if conditions in the code were met.
Its just a template by Google to show you/world about how you can handle clicks on Menu Items (Action Bar) in android.
If we talk about this particular case, then in this case they are handling the click for two menu items 1. Search 2.Settings.
To accomplish the above task they have used switch (you can also use if and else statements) to verify which item has been clicked.
switch (item.getItemId()) { // Here they are checking the Id of item been clicked
case R.id.action_search: // Here they are examining if search item is clicked
//openSearch(); // if above case satisfies, then they gonna invoke the openSearch() method.
Toast.makeText(getApplicationContext(), "Pit Bull", Toast.LENGTH_LONG).show();
return true;
case R.id.action_settings: // Here they are examining if action item is clicked
//openSettings(); // if above case satisfies, then they have invoked the openSettings() method.
Toast.makeText(getApplicationContext(), "Eminem", Toast.LENGTH_LONG).show();
return true;
You can do whatever you want to do inside these cases by replacing your own logic
e.g : You can show here a Toast Like this
Toast.makeText(getApplicationContext(), "Pit Bull", Toast.LENGTH_LONG).show();
Its good that you want to learn programming, but its necessary that you should have basic knowledge of java first otherwise it will be quite hard to understand/learn the Android.
Best of luck..
Put whatever other code you want, those are sample methods, in place of methods you can log something to logcat, as Log.w("Test", "search button clicked");
basically the case part contains the action to be performed on click of button, like you may start a new activity, print something, set a log, whatever code you want on click, you can put it in the case of that particular button.

Bitwise operators android

I'm new to bitwise operator, I don't know what are they use for, but I know the following:
5 & 3 = 1
because
0101 & 0011 = 0001
So yeah, I understand that we multiply each bit pair like 1 x 0 = 0, 1 x 1 = 1 and 0 x 0 = 0
Now when it comes to coding, I found the following code for onTouchEvent:
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction() & MotionEvent.ACTION_MASK;
switch(action) {
case MotionEvent.ACTION_DOWN : {
break;
}
case MotionEvent.ACTION_MOVE : {
break;
}
case MotionEvent.ACTION_POINTER_DOWN : {
break;
}
case MotionEvent.ACTION_POINTER_UP : {
break;
}
case MotionEvent.ACTION_UP : {
break;
}
}
return true;
}
Ok firstable, the part int action = event.getAction() & MotionEvent.ACTION_MASK; what is the value of action after the operation, and what does it means? why not just simply use action = event.getAction() what's the meaning.
second, I've never seen the use of {} to define a code block for a case: is this specific because we're using the bitwise and operator or this is something totally normal and I happen to just notice that you can use them?
The reason the event is masked is to remove unrelated bits from the event. Performing bitwise-and with ACTION_MASK isolates only those particular bits. This is how you combine and test status flags that are packed into an integer. If you did not mask it, then if any other bit is set on the event, you would not be able to easily test your actions for equality.
What this is actually doing is reserving a small number of bits for an action, like having a 3-bit integer (or whatever it actually is). The mask just sets the relevant bits, so that all other bits are thrown away (ie are unimportant).
As for the braces in case statements, that's fine. You can put braces just about anywhere - it creates a a block-scope level, where any new variables you create inside that block will only exist in the block. In case statements this is quite normal, and prevents a variable in one case from "falling through" to subsequent cases. For example:
switch(foo)
{
case 0:
int i = 42;
// do something with i
break;
case 1:
// The variable i is still in scope here, which is often not
// intentional (but can sometimes be useful)
}
To stop i from falling through:
switch(foo)
{
case 0:
{
int i = 42;
// do something with i
}
break;
case 1:
// The variable i defined above is not available here.
}
In your case, the braces are superfluous, but are probably there because the person who wrote the code has adopted this practice into their coding style. Most likely they've been burned by an unwanted side-effect before, or their compiler emits warnings about variable fall-through and they've decided to just use braces all the time. Personally, I think it's cleaner to only use them when necessary.
The event that comes back from event.getAction() is actually an integer. It contains more than just information about the type of action apparently. It probably contains flags that describe the action in more detail. And by passing all that detail in through an int, it saves the use of a class object to represent the action itself.
The mask is bitwise for the first byte in the integer. Only the first two bytes out of the eight. And for comparison purposes, you need to remove the upper parts of the integer before comparing it against the actions, which are themselves only using the bottom byte of an integer.
The upper parts of the event integer are still useful for other purposes when checking against them. So the mask is 0x000000ff representing that you only want information related to the action type at the bottom and the entire event takes up the rest of it with other useful information.

Getting proper input for password activity

I am preparing a password activity and I want to get the proper input for it.
I am using the code
while(counter<5){
switch(counter){
case 1:pwdField();
counter++;
break;
case 2:pwdField2();
counter++;
break;
case 3:pwdField3();
counter++;
break;
case 4:pwdField4();
counter++;
break;
}
}
pwdField are the methods that contain listeners for buttons. But for some reason only the third textView receives input. It doesnt break off after the input is received. What am i doing wrong?
Moved from comments:
Why do you have the while loop? If the while loop condition is met and counter is not negative then the loop will go into a case and break out of the loop, thus only going through it once. If the condition is not met then the loop will be iterated 0 times. Why not replace the while loop with an if statement?
You may not want to have the breaks in there but I don't know the intent of this snippet.

Categories

Resources