Android - checking for certain value does not - java

I am working on Android billing and trying to set the onPurchaseStateChange method correct, but it does not seem to be working.
#Override
public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
int quantity, long purchaseTime, String developerPayload)
{
if (purchaseState == PurchaseState.PURCHASED)
{
mOwnedItems.add(itemId);
if ( itemId != null && itemId.trim().equals("3") )
{
Intent myIntent = new Intent(ExtraHelpActivity.this, PsychologyActivity.class);
ExtraHelpActivity.this.startActivity(myIntent);
}
if ( itemId != null && itemId.trim().equals("4") )
{
Intent myIntent = new Intent(ExtraHelpActivity.this, NumberOfBusinessesActivity.class);
ExtraHelpActivity.this.startActivity(myIntent);
}
}
else
if (purchaseState == PurchaseState.CANCELED)
{
// purchase canceled
}
else
if (purchaseState == PurchaseState.REFUNDED)
{
// user ask for a refund
}
else
{
if ( itemId != null && itemId.equals("3") )
{
Intent myIntent = new Intent(ExtraHelpActivity.this, PsychologyActivity.class);
ExtraHelpActivity.this.startActivity(myIntent);
}
if ( itemId != null && itemId.equals("4") )
{
Intent myIntent = new Intent(ExtraHelpActivity.this, NumberOfBusinessesActivity.class);
ExtraHelpActivity.this.startActivity(myIntent);
}
}
So when the purchaseId is "4" or "3" and the purchaseState == PurchaseState.PURCHASED ....for some reason it does not seem to get into that if statement, and does not perform the intent to go to the next page?
Would anyone know why that happens? It seems very strange. Could it be a Java thing?
Thanks!

PurchaseState is not a primitive data type like int, long, float, etc so you should use:
purchaseState.equals(PurchaseState.PURCHASED)
instead of ==, just like you use with Strings:
string1.equals(string2) // Results you expect
is not the same as
string1 == string2 // Don't do this...

Related

I am having trouble when I run the java application and it can't execute as I expect

My application cannot find the roommate I added to the room, see sequence:
Please select one of the following options:
Add a room in the apartment[1]
Search for a room in the apartment[2]
Add a roommate to an existing room[3]
Check if a room has a roommate[4]
Count the number of existing rooms that have roommates living in them[5]
3
What is the name of this roommate?
kack
What is the surname of thid roommata?
han
What is the age of this roommate?
20
Which room you want to add this roommate in?[A]/[B]/[C]
b
The roommate was added to the room!
Do you want to continue using the App? (Y/N)
y
Please select one of the following options:
Add a room in the apartment[1]
Search for a room in the apartment[2]
Add a roommate to an existing room[3]
Check if a room has a roommate[4]
Count the number of existing rooms that have roommates living in them[5]
4
What is the ID of the room?[A]/[B]/[C]
b
Sorry! There is no roommate in this room.
I am not sure where I have to rewrite. I want to know which part is wrong and how I should rewrite my code. The code is following, and the first part is to add roommate and the second part is to check if there is a roommate in the room:
public boolean addRoommate(String pName, String pSurname, int pAge, char pID) {
boolean response = false;
if (roomA != null && roomA.getID() == (pID)) {
Roommate newRoommate = new Roommate(pName, pSurname, pAge);
response = true;
} else if (roomB != null && roomB.getID() == (pID)) {
Roommate newRoommate = new Roommate(pName, pSurname, pAge);
response = true;
} else if (roomC != null && roomC.getID() == (pID)) {
Roommate newRoommate = new Roommate(pName, pSurname, pAge);
response = true;
}
return response;
}
Here is the second part of the code, which is where I check for roommate:
public Roommate checkRoommate(char pID) {
Roommate response = null;
if (roomA != null && roomA.getID() == (pID) && roomA.getRoommate() != null) {
response = roomA.getRoommate();
} else if (roomB != null && roomB.getID() == (pID) && roomB.getRoommate() != null) {
response = roomB.getRoommate();
} else if (roomC != null && roomC.getID() == (pID) && roomC.getRoommate() != null) {
response = roomC.getRoommate();
}
return response;
}
You need to put the rommate into a rool, for example this way:
roomA.setRoomMate(newRoommate)

Best way to check specific result of 2 methods in Java

I have the following method
public Message JavaMethod(String id1, String id2)
In which I need to call a Dao class's method to verify that an user with the provided Id exist, and if it does not, create a message detailing the Id that couldn't be found on the database with the following method:
createMessage("Message string",Enum.TYPE,IdofMissingUser);
At first I thought of doing it like this:
public Message JavaMethod(String id1, String id2) {
if(Dao.findUser(id1) == null || Dao.findUser(id2) == null){
return createMessage("Error",Enum.Error,id1);
}else{
//do some other stuff
}
}
But obviously this way I won't know which of the ids has not been found.
So I went ahead and created an ugly if else cycle:
public Message JavaMethod(String id1, String id2) {
if (Dao.findUser(id1) == null) {
return createMessage("Error", Enum.Error, id1);
} else if (Dao.findUser(id2) == null) {
return createMessage("Error", Enum.Error, id2);
} else {
// Do stuff after veryfing users exists
return createMessage("All OK", Enum.OK, messageData);
}
}
But I'm not feeling really confident that this is the best solution for this basic issue.
What would you guys recommend in this case?
You could wrap the ids in a list and use a for loop:
public Message someMethod(String id1, String id2) {
for (String id: Arrays.asList(id1, id2)) {
if (Dao.findUser(id) == null) {
return createMessage("Error", Enum.Error, id);
}
}
// Do stuff after verifying users exists
return createMessage("All OK", Enum.OK, messageData);
}
If you're only ever going to have two IDs, you could deal with a shorthand boolean. Question is whether that makes it less readable though. E.g.
public Message JavaMethod(String id1, String id2) {
User user1 = Dao.findUser(id1);
User user2 = Dao.findUser(id2);
if(user1 == null || user2 == null){
return createMessage("Error",Enum.Error,user1 == null ? id1 : id2);
}else{
//do some other stuff
}
}
This also doesn't deal with if both of the IDs were null, for that you could extend it:
public Message JavaMethod(String id1, String id2) {
User user1 = Dao.findUser(id1);
User user2 = Dao.findUser(id2);
if(user1 == null || user2 == null){
return createMessage("Error",Enum.Error,user1 == null && user2 == null? both : user1 == null ? id1 : id2);
}else{
//do some other stuff
}
}
You'd need to define what you would return for the both variable
More details on the shorthand boolean annotation can be found here

Android check if multiple strings are not empty

I have a form and I put the forms data in an intent and then start a new activity and send the data with the intent, but I wanna do a check if the strings are empty I should display and error message. If the strings are not empty the activity can be started.
I've tried the following code but it doesn't seem to be working. If the field is empty it just starts the other activity
(I've tried with only 1 field for now, because I don't know how to to it for multiple fields)
//getting the field values
String firstname = editTextFirstname.getText().toString();
String lastname = editTextLastname.getText().toString();
String amount = editTextBedrag.getText().toString();
String timespan = spinnerPeriode.getSelectedItem().toString();
String iban = editTextIBAN.getText().toString();
if(firstname != null) {
//putting data in the intent
intent.putExtra(FIRSTNAME, firstname);
intent.putExtra(LASTNAME, lastname);
intent.putExtra(AMOUNT, amount);
intent.putExtra(TIMESPAN, timespan);
intent.putExtra(IBAN, iban);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
}
A cleaner way to do this is
public static boolean isAnyStringNullOrEmpty(String... strings) {
for (String s : strings)
if (s == null || s.isEmpty())
return true;
return false;
}
Then you can call it like this
if (isAnyStringNullOrEmpty(firstname, lastname, amount, timespan, iban)) {
Toast.makeText(MainActivity.this, "Oops, you forgot to fill in some fields!", Toast.LENGTH_SHORT).show();
} else {
}
Using apache commons, we can do this as:
boolean valid = StringUtils.isNoneEmpty(firstname, lastname, amount, timespan, iban)
Change
if(firstname != null)
to
if(!TextUtils.isEmpty(firstname) && !TextUtils.isEmpty(lastname) &&
!TextUtils.isEmpty(amount) &&!TextUtils.isEmpty(timespan) &&
!TextUtils.isEmpty(iban))
Java 8 + Apache Commons Lang only:
String firstname = editTextFirstname.getText().toString();
String lastname = editTextLastname.getText().toString();
String amount = editTextBedrag.getText().toString();
String timespan = spinnerPeriode.getSelectedItem().toString();
String iban = editTextIBAN.getText().toString();
boolean valid = Stream.of(firstname, lastname, amount, timespan, iban)
.allMatch(StringUtils::isNotBlank);
if(firstname != null && lastname != null && amount != null && timespan != null
&& iban != null & firstname.trim().isEmpty() && !lastname.trim().isEmpty() &&
!amount .trim().isEmpty() && !timespan.trim().isEmpty() && !iban.trim().isEmpty())
Using Java Stream API:
private boolean anyBlank(String...strings) {
return Stream.of(strings).anyMatch(string -> isBlank(string));
}

how to improve code quality (mostly duplicates)

I have a set of variables that was passed in by a mega method in an ancient legacy code.....
public List<type> check (String required, String sales, String report,
Long passId, Long seatId, String capName, String vCapName,
String attName, Long vid) {
if(required != null) {
goodA = method(required);
goodB = methodTwo(required);
goodC = methodThree(required);
}
if(sales != null) {
goodA = method(sales);
goodB = methodTwo(sales);
goodC = methodThree(sales);
}
if(report != null) {
goodA = method(report);
goodB = methodTwo(report);
goodC = methodThree(report);
if(passId != null)
... you got the point....
}
The variables that passed into check can only be 1 valid value all other variables will become null.
For example
check("Yes",null,null,null,null,null...)
or
check(null,null,null,13212L,null,null,null,null)
right now I am trying to rewrite this into something less repetitive and clean I was wondering if anyone can provide some ideas on how to do this.
How about something like this?
List<Object> items = Lists.newArrayList(required, sales, report,
capName, vCapName, attName);
for(Object item : items) {
if(item != null){
methodOne(item);
methodTwo(item);
methodThree(item);
}
}

How build sql query with many parameters from java code?

I have sql select with parameters:
SELECT * FROM tbl t WHERE t.name = ? AND t.age = ? AND t.number = ? AND ... AND t.last_parameter = ? order by t.some desc //many parameterss
I get parameters from form's fields and some fields may be empty. I build sql string:
String sqlStatementText;
MessageFormat sqlStatementTextTemplate = new MessageFormat(Queries.WAR_GET_REPORT_COUNT);
List<Object> parametrs = new ArrayList<>();
if (null == subscriberMSISDN || subscriberMSISDN.length() == 0) {
parametrs.add("");
} else {
parametrs.add(Queries.WAR_REPORT_CALLING_NUMBER);
}
if (null == operatorID || operatorID.length() == 0) {
parametrs.add("");
} else {
parametrs.add(Queries.WAR_REPORT_OPERATOR_AVAYA_ID);
}
if (null == operatorNickname || operatorNickname.length() == 0) {
parametrs.add("");
} else {
parametrs.add(Queries.WAR_REPORT_NICKNAME);
}
if (null == msg1 || msg1.length() == 0) {
parametrs.add("");
} else {
parametrs.add(Queries.WAR_REPORT_MSG1);
}
if (null == msg2 || msg2.length() == 0) {
parametrs.add("");
} else {
parametrs.add(Queries.WAR_REPORT_MSG2);
}
sqlStatementText = sqlStatementTextTemplate.format(parametrs.toArray());
ant them i do it:
try (Connection sqlConnection = connectionPool.getConnection();
PreparedStatement sqlStatment = sqlConnection.prepareStatement(sqlStatementText)) {
int paramID = 1;
sqlStatment.setInt(paramID++, 1);
sqlStatment.setDate(paramID++, new java.sql.Date(fromDate.getTime()));
sqlStatment.setDate(paramID++, new java.sql.Date(toDate.getTime()));
if (null != subscriberMSISDN && subscriberMSISDN.length() != 0) {
sqlStatment.setString(paramID++, subscriberMSISDN);
}
if (null != operatorID && operatorID.length() != 0) {
sqlStatment.setString(paramID++, operatorID);
}
if (null != operatorNickname && operatorNickname.length() != 0) {
sqlStatment.setString(paramID++, operatorNickname);
}
if (null != msg1 && msg1.length() != 0) {
sqlStatment.setString(paramID++, msg1);
}
if (null != msg2 && msg2.length() != 0) {
sqlStatment.setString(paramID++, msg2);
}
try (ResultSet resultSet = sqlStatment.executeQuery()) {
while (resultSet.next()) {
count = resultSet.getInt(1);
}
resultSet.close();
sqlStatment.close();
sqlConnection.close();
}
But i thig it not correctly. But I dont know how build sql query with many paramaters and if some parameters maybe empty.
Switch to an ORM. They will have some form of criteria-like object.
Use the param is null or column = param SQL syntax. select x from y where (? is null OR column1 = ?)
You need to set the value of the param twice, and the input value can not legitimately be null.
There is no way to do it, given the SQL statement you have.
You need to change the SQL statement WHERE conditions from things like t.name = ? to t.name = nvl(?, t.name). Then, you can bind a NULL there and the condition will always evaluate to true (so it's not acting as a filter -- which is what you want when the user leaves the field blank).
Or -- a better approach if you can do it, it's even better to use conditions like you've got them (e.g., t.name= ?), but build the conditions dynamically based on what fields the user give you. That is, for example, if the user leaves the "name" parameter blank, just omit the t.name = ? condition entirely.
That leaves you with a shorter SQL statement that makes the Oracle optimizer's job a little bit easier. With the t.name = nvl(?, t.name) approach I gave you above, you're relying on some pretty advanced optimizer features to get the best performance, because it's not immediately clear whether, say, it would be good or bad for the optimizer to use an index on t.name.

Categories

Resources