set Image Resource and if-else issue - if-statement

I am trying to change image shown in ImageView according to the String in TextView (excuse me for the nested if-else statements). In the tests that I have run, even though the value of st1 is "HKD", the flagName that get pass out from the nested if-else is still "#drawable/foreign_exchange".
I cannot seem to find the issue. Any help will be much appreciated. Thanks.
EditText etCurrency = findViewById(R.id.editTextCurrency);
String st1 = etCurrency.getText().toString();
if (st1=="HKD"){
flagName = "#drawable/flag_hong_kong";
}else if(st1=="IDR"){
flagName = "#drawable/flag_indonesia";
}else if(st1=="JPY"){
flagName = "#drawable/flag_japan";
}else if(st1=="KRW"){
flagName = "#drawable/flag_south_korea";
}else if(st1=="MYR"){
flagName = "#drawable/flag_malaysia";
}else if(st1=="NZD"){
flagName = "#drawable/flag_new_zealand";
}else if(st1=="PHP"){
flagName = "#drawable/flag_philippines";
}else if(st1=="THB"){
flagName = "#drawable/flag_thailand";
}else if(st1=="TWD"){
flagName = "#drawable/flag_taiwan";
}else flagName = "#drawable/foreign_exchange";
int imageResource = getResources().getIdentifier(flagName,null,this.getPackageName());
imageView.setImageResource(imageResource);

use .equals instead of ==
if (st1.equals("HKD"))

Related

Changing if-else into switch statements?

I am using multiple else/if statements and I want to use switch statements. I tried but don't know how to fill in multiple answers.
How can I convert the following else/if statements to switch?
if (this.state.item.type === 'dashboard') {
settings.view_name = this.state.view_name;
settings.layout = this.state.layout;
settings.inline_edit = this.state.inlineEdit;
settings.show_add = this.state.showAdd;
settings.tab_queries = this.state.tabQueries;
settings.carousel = this.state.carousel;
settings.template = this.state.template;
settings.sort = this.state.sort;
settings.templateOptions = this.state.templateOptions;
} else if (this.state.item.type === 'list_option_percentage_conditions') {
settings.pie_charts = this.state.pie_charts;
} else if (this.state.item.type === 'count_list_options') {
settings.count_list_field = this.state.count_list_field;
settings.date_field = this.state.date_field;
settings.use_creation_date = this.state.use_creation_date;
settings.scheme = this.state.scheme;
} else if (this.state.item.type === 'sum_fields') {
settings.sum_field = this.state.sum_field;
settings.scheme = this.state.scheme;
}
I want it to look something like this:
switch (this.state.iten.type) {
case "dashboard":
answer = "";
break;
case "list_option_percentage_conditions":
answer = "";
case "count_list_options":
answer = "";
break;
case "sum_fields":
answer = "";
break;
}

If else not working in android inside for and while loop

public void LoadRoutine() {
TableRow tbrow0 = new TableRow(getActivity());
//String[] mStrings = new String[9];
tbrow0.setBackgroundColor(Color.parseColor("#FFFFFF"));
tbrow0.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (String c : TimeSlotSummer) {
TextView tv0 = new TextView(getActivity());
tv0.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv0.setGravity(Gravity.CENTER);
tv0.setTextSize(12);
tv0.setHeight(40);
tv0.setWidth(76);
tv0.setBackgroundColor(Color.parseColor("#FFFFFF"));
tv0.setTextColor(Color.parseColor("#000000"));
tv0.setPadding(1, 1, 1, 1);
tv0.setText(c);
tv0.setBackgroundColor(R.id.tableRowid);
tbrow0.addView(tv0);
}
tableLayout.addView(tbrow0);
String dept = GlobalClass.userDepartment;
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getActivity());
databaseAccess.Open();
String faccode = GlobalClass.faculty_code;
Cursor cRoutine = databaseAccess.getRoutine("Sunday",dept);
if (cRoutine.getCount() == 0) {
Toast.makeText(getActivity(),"No Data in Table",Toast.LENGTH_LONG).show();
}
else{
while (cRoutine.moveToNext())
{
String[] mStrings = new String[10];
mStrings[0] = cRoutine.getString(2);
mStrings[1] = cRoutine.getString(4);
mStrings[2] = cRoutine.getString(5);
mStrings[3] = cRoutine.getString(6);
mStrings[4] = cRoutine.getString(7);
mStrings[5] = cRoutine.getString(8);
mStrings[6] = cRoutine.getString(9);
mStrings[7] = cRoutine.getString(10);
mStrings[8] = cRoutine.getString(11);
TableRow tbrow1 = new TableRow(getActivity());
tbrow1.setBackgroundColor(Color.parseColor("#FFFFFF"));
tbrow1.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (String cls:mStrings) {
TextView tv1 = new TextView(getActivity());
tv1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv1.setGravity(Gravity.CENTER);
tv1.setTextSize(12);
tv1.setWidth(75);
tv1.setHeight(37);
tv1.setBackgroundColor(Color.parseColor("#FFFFFF"));
tv1.setPadding(1, 1, 1, 1);
tv1.setBackgroundColor(R.id.tableRowid);
tv1.setText(cls);
tv1.setTextColor(Color.parseColor("#FF0000"));
if(cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));
tbrow1.addView(tv1);
}
tableLayout.addView(tbrow1);
}
}
}
Inside the last for loop, without if-else, it works properly, but with if-else it is not working, that is apps shut down and mobile restart again.
Any one help me, I want to check some substring, then text color will change, otherwise color normal.
It would help if you posted a stack trace but if the crash occurs here:
if(cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));
The only explanation is that you get a NullPointerException on cls because tv1 is obviously not null if it did not crash before.
Use this code instead:
if(cls != null && cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));

Omnet++ A cRuntimeError exception is about to be thrown std::length_error: basic_string::_M_create

so I get this error when i run my code
Error in module (TraCIDemoRSU11p) RSUExampleScenario.rsu[0].appl (id=8) at event #4000, t=45.40151998544: std::length_error: basic_string::_M_create.
TRAPPING on the exception above, due to a debug-on-errors=true configuration option. Is your debugger ready?
it shows that I have this issue at this line after looping multiple times
VehTD = *iteh2;
please be informed that I'm trying to remove from this vehicle list to another vehicle list and delete the moved items.
std::list<std::pair<std::string,std::string>>::const_iterator iteh2 = waitingList.begin();
for (std::list<std::pair<std::string,std::string>>::const_iterator iteh = waitingList.begin(); iteh != waitingList.end() && !waitingList.empty(); ){
iteh2 = iteh;
cout<<"Veh ID TF 1:";
cout<<VehTD.first<<endl;
cout<<VehTD.second<<endl;
VehTD = *iteh2;
cout<<"Veh ID TF 2:";
cout<<VehTD.first<<endl;
cout<<VehTD.second<<endl;
CompareResult3 = Locks(Locked,VehTD.second);
if(CompareResult3.second == 1 || CompareResult3.second == 2 ){
//remove from waiting and add to crossing
std::string ehk = "";
simtime_t VehicleT = simTime();
std::pair<std::pair<std::string, std::string>, simtime_t> VehicleWithTime;
crossingList.push_back(VehTD);
iteh2 = waitingList.erase(iteh2);
}
else{
++iteh;
}
}
}
I'm using Oment++ 5.0 and veins 4.4
I put a try and catch at this function, and it seems that the exception happens towards the end of the list.
Update:
I have this output:
WCounter 1
WCounter 2
Moving from waiting list Timer Function Exception
WCounter 1
WCounter 2
WCounter 3
Moving from waiting list Timer Function Exception
WCounter 1
WCounter 2
Moving from waiting list Timer Function Exception
The WCounter is a variable to show how many times it looped before having the exception at the point explained earlier.
based on request I added the locks function:
std::pair<std::list<std::string>,int> TraCIDemoRSU11p::Locks(std::list<std::string> alreadyLocked, std::string laneNo){
bool debugL;
//create variables for the lanes for easier use
try{
debugL = false;
zero = "171270266#0_0";
one = "171270266#0_1";
two = "-171270025#1_0";
three = "-171270025#1_1";
four = "-171270266#1_0";
five = "-171270266#1_1";
six = "171270025#0_0";
seven = "171270025#0_1";
//create lists of locks
Locks0 = Locks1 = Locks2 = Locks3 = Locks4 = Locks5 = Locks6 = Locks7 = RequestToLock = {};
CounterOfSimilarLanes = 0;
//set of 0 ,Locks0;
Locks0.push_back(zero);
Locks0.push_back(five);
Locks0.push_back(seven);
//set of 1 ,Locks1;
Locks1.push_back(one);
Locks1.push_back(three);
Locks1.push_back(six);
//set of 2 ,Locks2;
Locks2.push_back(one);
Locks2.push_back(two);
Locks2.push_back(seven);
//set of 3 ,Locks3;
Locks3.push_back(zero);
Locks3.push_back(three);
Locks3.push_back(five);
//set of 4 ,Locks4;
Locks4.push_back(one);
Locks4.push_back(three);
Locks4.push_back(four);
//set of 5 ,Locks5;
Locks5.push_back(two);
Locks5.push_back(five);
Locks5.push_back(seven);
//set of 6 ,Locks6;
Locks6.push_back(three);
Locks6.push_back(five);
Locks6.push_back(six);
//set of 7 ,Locks7;
Locks7.push_back(one);
Locks7.push_back(four);
Locks7.push_back(seven);
//This is the request to lock from the vehicle using its lane number
if (laneNo == zero ){
RequestToLock.insert(RequestToLock.end(),Locks0.begin(),Locks0.end());
}else if (laneNo == one){
RequestToLock.insert(RequestToLock.end(),Locks1.begin(),Locks1.end()) ;
}else if (laneNo == two){
RequestToLock.insert(RequestToLock.end(),Locks2.begin(),Locks2.end()) ;
}else if (laneNo == three){
RequestToLock.insert(RequestToLock.end(),Locks3.begin(),Locks3.end()) ;
}else if (laneNo == four){
RequestToLock.insert(RequestToLock.end(),Locks4.begin(),Locks4.end()) ;
}else if (laneNo == five){
RequestToLock.insert(RequestToLock.end(),Locks5.begin(),Locks5.end()) ;
}else if (laneNo == six){
RequestToLock.insert(RequestToLock.end(),Locks6.begin(),Locks6.end()) ;
}else if (laneNo == seven){
RequestToLock.insert(RequestToLock.end(),Locks7.begin(),Locks7.end()) ;
}
} //if the already locked from the controller is empty so we take the requested lock
catch(const std::exception &e){
cout<<"Preparing Locks Algorithm Exception"<<endl;
}
try{
if (alreadyLocked.empty()){
markOfLocks = 0;
alreadyLocked.insert(alreadyLocked.end(),RequestToLock.begin(),RequestToLock.end()) ;
Locked.insert(Locked.end(),RequestToLock.begin(),RequestToLock.end()) ;
if (debugL == true){
cout<<"First Lock in the locking algorithm"<<endl;
// dumplistLock(Locked);
}
ReturnOfLocks = make_pair(alreadyLocked,markOfLocks);
}else{ // if the already locked by the controller isnt empty, so we need to compare the request with it
//Search for similar items in the 2 lists
for(std::list<std::string>::/*const_*/iterator it_1 = alreadyLocked.begin();it_1 != alreadyLocked.end();)
{
for(std::list<std::string>::/*const_*/iterator it_2 = RequestToLock.begin(); it_2 != RequestToLock.end();)
{
if(*it_1 == *it_2)
{
++CounterOfSimilarLanes;
}
++it_2;
}
++it_1;
}
if (RequestToLock == alreadyLocked){
markOfLocks = 1;
Locked.clear();
Locked = {};
Locked.insert(Locked.end(),alreadyLocked.begin(),alreadyLocked.end()) ;
if (debugL == true){
cout<<"Same Lane"<<endl;
dumplistLock(Locked);
}
ReturnOfLocks = make_pair(alreadyLocked,markOfLocks);
}else if(CounterOfSimilarLanes == 0){ //if the request is concurrent meaning totally different locks
markOfLocks = 2;
//alreadyLocked.insert(alreadyLocked.end(),RequestToLock.begin(),RequestToLock.end()) ;
Locked.clear();
Locked = {};
Locked.insert(Locked.end(),alreadyLocked.begin(),alreadyLocked.end()) ;
if (debugL == true){
cout<<"Concurrent Lane"<<endl;
dumplistLock(Locked);
}
}else if(CounterOfSimilarLanes == 1 || CounterOfSimilarLanes == 2){ // if there's a similarity is 1 lock at least so it leads to conflict
markOfLocks = 3;
Locked.clear();
Locked = {};
Locked.insert(Locked.end(),alreadyLocked.begin(),alreadyLocked.end()) ;
if (debugL == true){
cout<< "opposite Lane"<<endl;
dumplistLock(Locked);
}
ReturnOfLocks = make_pair(alreadyLocked,markOfLocks);
}else{
markOfLocks = 1;
Locked.clear();
Locked.insert(Locked.end(),alreadyLocked.begin(),alreadyLocked.end()) ;
if (debugL == true){
cout<<"default case"<<endl;
dumplistLock(Locked);
}
ReturnOfLocks = make_pair(alreadyLocked,markOfLocks);
}
}
}catch(const std::exception &e){
cout<<"Lock Cases Exceptions"<<endl;
}
try{
return ReturnOfLocks;
}catch(const std::exception &e){
cout<<"No Return of Locks in Locks Alg Exception"<<endl;
}
}
so I changed the for loop to a while loop and it didn't show an exception, and not sure why.
therefore the loop looks like this now:
//while loop instead.
std::list<std::pair<std::string,std::string>>::iterator iterwil = waitingList.begin();
std::pair<std::string, std::string> Vehwil ;
while (iterwil != waitingList.end()){
Vehwil = *iterwil;
CompareResult3 = Locks(Locked,Vehwil.second);
if(CompareResult3.second == 1 || CompareResult3.second == 2 ){
crossingList.push_back(Vehwil);
waitingList.erase(iterwil++);
}else{
++iterwil;
}
}
if someone has a valid reason to enlighten me on why the while loop works with no exception unlike the for loop that would be great. ^^"
You should use iterator instead of const_iterator because you modify (i.e. delete) indicated element.
By the way, in the code iteh2 is unnecessary - iteh is sufficient as well as VehicleT and ehk variables are not used and may be removed.

Refactoring messy if else statement

I am working on a legacy code base which has the following snippet:
if ((results[0].Length == 0))
customerName = "";
else
customerName = results[0].Substring(18);
if ((results[1].Length == 0))
meterSerialNumber = "";
else
meterSerialNumber = results[1];
if ((results[2].Length == 0))
customerID = "";
else
customerID = results[2];
if ((results[3].Length == 0))
meterCreditAmount = "";
else
meterCreditAmount = results[3];
if ((results[4].Length == 0))
debtInstallmentDeduction = "";
else
debtInstallmentDeduction = results[4];
if ((results[5].Length == 0))
vatOnEnergyAmount = "";
else
vatOnEnergyAmount = results[5];
if ((results[6].Length == 0))
vatOnDebt = "";
else
vatOnDebt = results[6];
if ((results[7].Length == 0))
outstandingDebtAmount = "";
else
outstandingDebtAmount = results[7];
if ((results[8].Length == 0))
tariffCategory = "";
else
tariffCategory = results[8];
if ((results[9].Length == 0))
tariffId = "";
else
tariffId = results[9];
if ((results[10].Length == 0))
encryptedToken1 = "";
else
encryptedToken1 = results[10];
if ((results[11].Length == 0))
encryptedToken2 = "";
else
encryptedToken2 = results[11];
if ((results[12].Length == 0))
encryptedToken3 = "";
else
encryptedToken3 = results[12];
if ((results[13].Length == 0))
encryptedToken4 = "";
else
encryptedToken4 = results[13];
if ((results[14].Length == 0))
systemMessage = "";
else
systemMessage = results[14];
if ((results[15].Length == 0))
customerMessage = "";
else
customerMessage = results[15];
if ((results[16].Length == 0))
predefinedMessage = "";
else
predefinedMessage = results[16];
if ((results[17].Length == 0))
transactionAcknowledgeNumber = "";
else
transactionAcknowledgeNumber = results[17];
What would be the best way to refactor this for acceptable coding standards? Would it be acceptable to make this a case statement instead?
This is not a case-wise execution so it can't be refactored to a switch-case. However it can be converted to functional code and then it factored out into a separate method so that the "ugly" part is hidden behind a method call.
Step#1 - Making the code functional
Here, we rewrite the code by following functional code writing practices. The rewritten code will look like:
customerName = (results[0].Length == 0) ? "" : results[0].Substring(18);
meterSerialNumber = (results[1].Length == 0) ? "" : results[1];
customerID = (results[2].Length == 0) ? "" : results[2];
meterCreditAmount = (results[3].Length == 0) ? "" : results[3];
debtInstallmentDeduction = (results[4].Length == 0) ? "" : results[4];
vatOnEnergyAmount = (results[5].Length == 0) ? "" : results[5];
.
.
.
transactionAcknowledgeNumber = (results[17].Length == 0) ? "" : results[17];
There are numerous advantages of writing the code this way. Important ones include:
terseness of code;
values being initialized at one place (by means of ternary operator) instead of two (one in if and another in else clause).
Step#2 - Factoring out the method
Now that the values are being initialized functionally, you can create a class (or you may be already having this class) containing the properties customerName, meterSerialNumber, ..., transactionAcknowledgeNumber. Either the constructor of the class can be designed to read the results and populate the class members or you may write a method to read the results. So it will look like:
ResultValues resultVal = new ResultValues();
resultVal.Read(results);
.
.
.
//Accessing the values later in the code
Print(resultVal.customerName);
...
PS:
1. I admit that ResultValues may not be a good class to make. Alternatively, you may create multiple classes by clubbing the related data and then have the Read() method of those classes read the values from results.
2. The essential idea of Step#2 is to factor out the "ugly" part to another simple and readable method call(s).

arc4random() stopped working after project update, Thread 1: EXC_ARITHMETIC

I got a warning on xcode 6.0.1 that I needed to update my project, so I did...
...but then I got issues with arc4random() % instead
Everything was working fine before this update, but now I get the following message:
"Thread 1: EXC_ARITHMETIC (code = EXC_1386_DIV, Subcode = 0x0) and the game crashes.
I tried with arc4random_uniform but the game seems to "pause" and nothing happens. What I mean is that I could see that it entered the if(bType == pt || bType == pl) statement but there is seems to "pause" and loop endlessly.
any suggestions?
-(void)placeInGrid:(CGPoint)place pt:(int)pt pl:(int)pl amount:(int)amountOfbricks{
CCLOG(#"BRICKS:placeInGrid");
//CCLOG(#"pt %d", pt);
//CCLOG(#"pl %d", pl);
int bType = arc4random() % amountOfbricks;
//int bType = arc4random_uniform(amountOfbricks);
if(bType == pt || bType == pl){
CCLOG(#"bType == pt || bType == pl");
[self placeInGrid:place pt:pt pl:pl amount:amountOfbricks];
return;
}
else{
CCLOG(#"else");
CCSpriteBatchNode * b = (CCSpriteBatchNode *)[theGame getChildByTag:kSSheet];
mySprite = [CCSprite spriteWithBatchNode:b rect:[self setBrickType:bType]];
[b addChild:mySprite z:1];
self.bricksType =bType;
[self.mySprite setPosition:place];
}
}
UPDATE:
the if-else statement below looks for saved data at the beginning of the game, to see if it´s a saved game or a new game.
The problem as it seems, after the project update is that the game thinks that there is already saved data and it goes to the first if statement ( if(gameData)), causing amountofbricks to be equal to 0, instead of going into the else statement where amountofbricks is equal to 4.
I don´t know how to solve this issue.
if ([[GameManager sharedGameManager] isContinuePressed] == NO && [[GameManager sharedGameManager] isNewPressed] == YES) {
if(gameData){
CCLOG(#"gameData && isContinuePressed == NO && isNewPressed == YES");
//Set the local instance of myobject to the object held in the gameState filler with the key "myObject"
level = 1;
[[GameManager sharedGameManager] setHScore:[decoder decodeIntegerForKey:#"HighScore"]];
highscore = [[GameManager sharedGameManager] ReturnHScore];
countTime = 300;
AmountOfBricks = [[GameManager sharedGameManager] ReturnAmountOfBricks];
BeginningOfGame = YES;
CCLOG(#"AmountOfBricks %d", AmountOfBricks);
}
else{
CCLOG(#"!gameData && isContinuePressed == NO && isNewPressed == YES");
if([[GameManager sharedGameManager]isThereASavedGame] ==YES){
CCLOG(#"isThereASavedGame == YES");
score = 0;
highscore = [[GameManager sharedGameManager] ReturnHScore];
level = 1;
countTime = 300;
AmountOfBricks = 4;
BeginningOfGame = YES;
CCLOG(#"AmountOfBricks %d", AmountOfBricks);
}
else{
CCLOG(#"isThereASavedGame == NO");
score = 0;
highscore = 0;
level = 1;
countTime = 300;
AmountOfBricks = 4;
BeginningOfGame = YES;
CCLOG(#"AmountOfBricks %d", AmountOfBricks);
}
}
}
UPDATE: I found the issue.
the issue was in my game manager.m file.
NSMutableData *gameData;
NSKeyedUnarchiver *decoder = nil;
NSString *documentPath = [documentsDirectory stringByAppendingPathComponent: #"gameState.dat"];
gameData = [NSData dataWithContentsOfFile:documentPath];//before the update, I as using this line. was working perfectly. after the update I got a warning on this line "incompatible pointer" and xcode recommended to update to the line below but the line below started to return a zero value. which caused the game to crash.
//gameData = [NSMutableData dataWithData:[NSData dataWithContentsOfFile:documentPath]];
I wager amountOfBricks is 0. You can't modulo by 0 like you can't divide by 0.