Android simple methods not working? - java

I have a spinner where the user can select something. When they do, it calls switchCat() which then calls chooseView() and based on the int passed will do something different. In this case it loads a different set of array strings.
However, whenever I run it, I will ONLY see the strings from R.array.array0, so the first if in chooseView(). csArray is set nowhere else. I am calling chooseView() onCreate.
I am a novice. Thank you!
Spinner item selected
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (synthetic) {
synthetic = false;
return true;
}
switchCat(itemPosition);
return true;
}
switchCat();
public void switchCat(int i) {
if(i == 0) {
chooseView(0);
}
else if(i == 1) {
chooseView(1);
}
}
chooseView()
public void chooseView(int i) {
if(i == 0) {
CharSequence[] csArray = getResources().getTextArray(R.array.array0);
for (CharSequence s : csArray) {
mArrayList.add(s);
}
}
if(i == 1) {
CharSequence[] csArray = getResources().getTextArray(R.array.array1);
for (CharSequence s : csArray) {
mArrayList.add(s);
}
}
}

It looks like you are adding items to your ArrayList. Are you sure you don't mean to get rid of old ones as well prior to adding? If you don't, they will remain in the list when chooseView() is called. In chooseView(), simply call mArrayList.clear() before your if statements. This, of course, assumes that your ListView is dependent on mArrayList.

Whenever you run first time it will give correct output,another time you arraylist will add the values with previous one,so every time you want's to clear the arraylist for get a correct output.
public void switchCat(int i) {
myArrayList.clear();
if(i == 0) {
chooseView(0);
}
else if(i == 1) {
chooseView(1);
}
}

Related

Using booleans with set and get methods

To summarize I am making a program for a metro ticket system. and I am using set and get methods for it, when it comes to boolean values (since I need to validate that the person enters enough money for the ticket) how am i supposed to put in the main class( it is defined in brain) using the set method and an if statement.Here is a little fraction of the entire code and the rest is on github(https://github.com/alexxei4/subwayticket). The main is basically the class that will be used for interaction with the user and the brain is where alot of the actions are defined.All help is appreciated, please and thank you.
if (Choice1a == 10){
if(subway1.ticketcounter1(true);){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
if(subway1.ticketcounter1(false);){
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
This is not how you evaluate boolean values, you just place the value in an if statement and it will proceed if true and refuse if false, also there is no need to duplicate the statement when you can just place an else block to handle situations that are not true:
if(subway1.ticketcounter1) {
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
else {
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
Also do not include semicolons in if statements, that's incorrect syntax. Read more about how to use use boolean values here: https://codingbat.com/doc/java-if-boolean-logic.html
EDIT:
After reading through your Github code I see that ticketcounter1 indeed is a method, but what it's doing is trying to change the value of ticketcounter1 like it's a referenced object, but boolean are primitive data types and can't be referenced, and even if they could it still wouldn't work because Java is a pass-by-value language. Read here for more information on that.
public void ticketcounter1(boolean ticketcounter1){
if (credit1 > total1){
ticketcounter1 = true;
}
else {
ticketcounter1 = false;
}
}
public void ticketcounter2(boolean ticketcounter2){
if (credit2 > total2){
ticketcounter2 = true;
}
else {
ticketcounter2= false;
}
Like the other answer said you should be returning the value as boolean instead of trying to change it:
public boolean ticketcounter1(){
if (credit1 > total1){
return true;
}
else {
return false;
}
}
public boolean ticketcounter2(){
if (credit2 > total2){
return true;
}
else {
return false;
}
}
But all in all your code demonstrated fundamental flaws in understanding how the language works, I would suggest picking up a good Java for beginners kind of book or do some introductory online tutorials. Here is a good place to start your learning journey: https://docs.oracle.com/javase/tutorial/java/index.html
You code is like this
public void ticketcounter1(boolean ticketcounter1){
if (credit1 > total1){
ticketcounter1 = true;
}
else {
ticketcounter1 = false;
}
}
public void ticketcounter2(boolean ticketcounter2) {
if (credit2 > total2){
ticketcounter2 = true;
}
else {
ticketcounter2= false;
}
}
It should be like this. Instead of using the variable and passing it though parameter. Use getter. Besides that your code won't run since subway1.ticketcounter1(true) is giving nothing. It is only changing variables stored in Brain.java. No information is being sent to main.
public boolean ticketcounter1(){
if (credit1 > total1){
return true;
}
else {
return false;
}
}
public boolean ticketcounter2(){
if (credit2 > total2){
return true;
}
else {
return false;
}
}
You can create functions without parameters. I don't know what were you trying to do?
if (Choice1a == 10){
if(subway1.ticketcounter1()){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
if(subway1.ticketcounter1()){
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
}
subway1.ticketcounter1() will give either true and false. Do not use ; in if statement condition. ; ends the statement. Check this guide to learn about use of semi-colon If you do want to use ; The code should look like this
if (Choice1a == 10){
boolean ticketCounter1 = subway1.ticketcounter1();
if(ticketCounter1){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
} else {
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
}
P.S You don't need two ifs if-else would be better in this case
if(condition) {
// Conditions is true
} else {
// Condition is false
}

Go ahead only if (condition)

I have this code
spinRoullete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (errors()){
something
return;}
if (!errors()){
something else}
And this is for errors
private boolean errors() {
if (Rone.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
} else {
nr1.setError(null);
}
} if (Rtwo.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
} else {
nr1.setError(null);
}
if (nr2.getText().length() == 0) {
nr2.setError("");
} else {
nr2.setError(null);
}
}
Something here it's wrong and I don't know what .. The texterrors appears, and disappear when I complete the nr1, or nr2 (edittexts) but something it's wrong with the second if from onClick. When the errors disappear I want to go forward to that second if ( that with something else).. What should I edit to do this?
First off, minor optimization improvement: You have this code (formatted for improved readability, same code):
if (errors()){
something...
return;
}
if (!errors()){
something else...
}
But you don't need that least one since you have a return statement:
if(errors()){
something
return;
}
something else...
The method is called once instead of twice if there isn't an error, so you avoid problems there.
But you never return any visible value from errors(). Most likely, you have return true at the bottom, meaning it always goes into the first if statement. Simply change the method:
private boolean errors() {
boolean i1 = false;//if no errors, return false
if (Rone.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
i1 = true;//There is at least one error
} else {
nr1.setError(null);
}
}
if (Rtwo.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
i1 = true;//there is at least one error
} else {
nr1.setError(null);
}
if (nr2.getText().length() == 0) {
nr2.setError("");
return true;//This is the last thing that can happen, so just return true. There is at least one error, this one
} else {
nr2.setError(null);
return i1;//there could have been an error earlier, so return i1
}
}
return i1;//and if the last box isn't checked, return i1 here
}
Most likely, you have return true at the bottom of the method. That means it will always go into the first if-statement and return even if there are no errors.
And you should really start looking into indentation conventions, some of the code you posted is very hard to read because of that

When is IWizard.canFinish executed

I have overridden the canFinish() method of IWizard. The API can be found here
Here is my code:
#Override
public boolean canFinish(){
if(templatePage.isPageComplete()
&& jenkinsPage.isPageComplete()
&& containerPage.isPageComplete()
&& dataSourcePage.isPageComplete()
&& queuePage.isPageComplete()
&& deploymentPage.isPageComplete()){
return true;
}
else if(model.isDeployOnly()){
return true;
}
return false;
}
There are other methods like addPages() that are also executed.
Really, I want to know when canFinish() is executed? And is there a list of the order in which they are executed?
canFinish is called by the WizardDialog whenever it needs to update the buttons on the button bar (the Back, Next and Finish button). There will be calls when the wizard is first shown and when you move between pages. Individual wizards can also call IWizardContainer.updateButtons whenever they want the button status updated.
Note: the default code for canFinish is:
public boolean canFinish() {
// Default implementation is to check if all pages are complete.
for (int i = 0; i < pages.size(); i++) {
if (!pages.get(i).isPageComplete()) {
return false;
}
}
return true;
}
so if you just want to call isPageComplete on all your pages just call super.canFinish

Replacing if else with OO aproach

Lets say I have:
if (count <= instance.getFCount()) {
//do something and return String
} else if (count <= instance.getFSCount()) {
//do something and return String
} else if (count <= instance.getTCount()) {
//do something and return String
} else if (count <= instance.getOCount()) {
//do something and return String
}
I am thinking how can I replace this code into something more object oriented. The problem is that if I would have statement like this:
if (count <= 0) {
//do something and return String
} else if (count <= 1) {
//do something and return String
} else if (count <= 2) {
//do something and return String
} else if (count <= 3) {
//do something and return String
}
I could replace it with some factory pattern or enum based approach because my values 0, 1, 2, 3 would always be static. For e.g. I would create a map to hold the class against the number, then if my count is 0 I would know that I need to create an instance from the class which was mapped with zero and so on.
But now I am thinking if there is any way to be done if I don't have the static values in if condition, because for e.g. what is returned to this: instance.getOCount() might be different depending on the configuration.
Could you give me some thoughts how to achieve this?
When you have lots of different if else statements, you can employ a Strategy Pattern. This helps you create manageable code that conforms to the best practice.
I believe there's no need to replace such a simple logic with a design pattern, it's not justified. A switch would be an improvement (assuming count is an integer), but why create a bunch of classes? it'd be justified only if each one had additional, different behavior.
If you use a NavigableMap such as a TreeMap, the keys being your thresholds and values being Callables, you'll be able to retrieve the appropriate Callable and invoke it, all in a one-liner. The relevant method is NavigableMap#ceilingEntry.
final NavigableMap<Integer, Callable<String>> strats = new TreeMap<>();
...
return strats.ceilingEntry(val).getValue().call(args);
I don't think using patterns is the solution here...everything will be harder to read than your original code. But if you are sure, this is one option:
Lets say your instance belongs to a class User. Create an interface
public interface IDynamicAction<T> {
boolean select(T t);
String action(T t);
}
Make a list
List<IDynamicAction<User>> actions = new ArrayList<IDynamicAction<User>>();
actions.add(new IDynamicAction<User>() {
#Override
public boolean select(User instance) {
return count <= instance.getFSCount();
}
#Override
public String action(User t) {
System.out.println("count <= instance.getFSCount()");
return "count <= instance.getFSCount()";
}
});
actions.add(new IDynamicAction<User>() {
#Override
public boolean select(User instance) {
return count <= instance.getTCount();
}
#Override
public String action(User t) {
System.out.println("count <= instance.getTCount()");
return " count <= instance.getTCount()";
}
});
actions.add(new IDynamicAction<User>() {
#Override
public boolean select(User instance) {
return count <= instance.getOCount();
}
#Override
public String action(User t) {
System.out.println("count <= instance.getOCount()");
return " count <= instance.getOCount()";
}
});
And execute your code with
for(IDynamicAction<User> action : actions){
if(action.select(instance)){
String s = action.action(instance);
System.out.println(s);
break;
}
}
Notice the break, I'm assuming based in your code only one action can execute
If you don't need a return value you may use an abstract class instead of an interface and make the if(select) action(); a part of the AbstractDynamicAction class the code will be nicer
Java7 does not really help doing that kind of stuff. Closures would make this things easier on the eye...but IMHO, your original multiple IF is the way to go.

Ways to check if an ArrayList contains only null values

I was looking through the code for an old Android application of mine, and I saw one thing I did to the effect of this:
boolean emptyArray = true;
for (int i = 0; i < array.size(); i++)
{
if (array.get(i) != null)
{
emptyArray = false;
break;
}
}
if (emptyArray == true)
{
return true;
}
return false;
There has to be a more efficient way of doing this -- but what is it?
emptyArray is defined as an ArrayList of Integers, which are inserted with a random number of null values (And later in the code, actual integer values).
Thanks!
Well, you could use a lot less code for starters:
public boolean isAllNulls(Iterable<?> array) {
for (Object element : array)
if (element != null) return false;
return true;
}
With this code, you can pass in a much wider variety of collections too.
Java 8 update:
public static boolean isAllNulls(Iterable<?> array) {
return StreamSupport.stream(array.spliterator(), true).allMatch(o -> o == null);
}
There is no more efficient way.
The only thing is you can do, is write it in more elegant way:
List<Something> l;
boolean nonNullElemExist= false;
for (Something s: l) {
if (s != null) {
nonNullElemExist = true;
break;
}
}
// use of nonNullElemExist;
Actually, it is possible that this is more efficient, since it uses Iterator and the Hotspot compiler has more info to optimize instead using size() and get().
It's not detection of contains only null values but it maybe be enough to use just contains(null) method on your list.
Simply Check it worked for me. Hope will work fine for you too!
if (arrayListSubQues!=null){
return true;}
else {
return false }
I use to do something like this :
// Simple loop to remove all 'null' from the list or a copy of the list
while array.remove(null) {
array.remove(null);
}
if (CollectionUtils.isEmpty(array)) {
// the list contained only nulls
}

Categories

Resources