Android check if multiple strings are not empty - java

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));
}

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)

How to extract a very specific sets of string parts from QR decoded string?

I needed to pick specific parts of a very big string (that's being decoded from a QR code) to set as text in TextView elements in Android.
//*these are the parts of the string whose corresponding values I need as a text for my TextViews.*
String uid, name, gname, gender, house, street, ps, po, dist, subdist, state, pin, address, dob;
//*this 'string' object holds the decoded qr string*
String string = "uid="001" name="Akbar Shah" gender="M" yob="1989" gname="Jahangir Shah" co="S/O: Jahangir Shah" house="45/5" street="Huzurey Ala Street" vtc="Alibagh" po="Bagnan" dist="Faridabad" subdist="Alamgarh" state="Andhra" pc="6754674" dob="15/04/89"";
//*this is where I am using substring() to get a specific part of the string value*
uid = string.substring(string.indexOf("uid=")+5, string.indexOf("name=")-2);
name = string.substring(string.indexOf("name=")+6, string.indexOf("gender=")-2);
gname = string.substring(string.indexOf("gname=")+7, string.indexOf("co=")-2);
gender = string.substring(string.indexOf("gender=")+8, string.indexOf("yob=")-2);
house = string.substring(string.indexOf("house=")+7, string.indexOf("street=")-2);
street = string.substring(string.indexOf("street=")+8, string.indexOf("vtc=")-2);
ps = string.substring(string.indexOf("vtc=")+5, string.indexOf("po=")-2);
po = string.substring(string.indexOf("po=")+4, string.indexOf("dist=")-2);
dist = string.substring(string.indexOf("dist=")+6, string.indexOf("subdist=")-2);
subdist = string.substring(string.indexOf("subdist=")+9, string.indexOf("state=")-2);
state = string.substring(string.indexOf("state=")+7, string.indexOf("pc=")-2);
pin = string.substring(string.indexOf("pc=")+4, string.indexOf("dob=")-2);
dob = string.substring(string.indexOf("dob=")+5, string.indexOf("/>")-1);
//*this is where I have concatenated the whole address parts into one*
address = house+", "+street+", \nPS - "+ps+", \nPO - "+po+", \nDistrict - "+dist+", \nSub-Division - "+subdist+", \nState - "+state+", \nPin Code - "+pin;
TextView tv_uid, tv_name, tv_gName, tv_gender, tv_address, tv_dob;
//*this is where I then setText those substrings for appropriate TextViews*
tv_uid.setText(uid);
tv_name.setText(name);
tv_gName.setText(gname);
tv_gender.setText(gender);
tv_address.setText(address);
tv_dob.setText(dob);
The way I have done this can only work if the decoded QR string format remains the same, i.e. if the string decoded now is this:
String string = "uid="001" name="Akbar Shah" gender="M" yob="1989" gname="Jahangir Shah" co="S/O: Jahangir Shah" house="45/5" street="Huzurey Ala Street" vtc="Alibagh" po="Bagnan" dist="Faridabad" subdist="Alamgarh" state="Andhra" pc="6754674" dob="15/04/89"";
Then, my way of extracting won't work if the string looks something like this:
String string = "uid="002" name="Amar Tripathi" gender="M" yob="1990" vtc="Alibagh" po="Bagnan" dist="Faridabad" state="Andhra" pc="6754674" dob="15/04/89"";
Or, like this:
String string = "uid="003" name="Anthony Gonzalis" gender="M" yob="1985" gname="Jahangir Shah" house="45/5" street="Huzurey Ala Street" lm="Behind the Meat shop" loc="Galianwalabagh" vtc="Alibagh" dist="Faridabad" state="Andhra" pc="6754674" dob="15/04/89"";
As you may have already noticed, substring() cannot be used universally for all cases because the last two string values have some parts missing in them. So if I specify to extract a particular substring which is sandwiched between gname and co, except for the first case, in the last two cases it won't be able to find co and hence the execution of the code line return error.
Is there a better way to do it?
P.S. Can I just extract all the string parts from inside " "?
E.g. "001" is the part of the string from which I just want to get the 001 part which is inside the double quotes.
you could use a regex, for example "\w*="([^"]*(?="))". This checks the following:
\w* matches word-characters (like letters and numbers) until
= the '=' is reached which simply matches the character '=',
[^"]* first matches the^'"'-character (which represents the opening '"'-character) and then every character that is not '"' until
(?=") is reached which checks if the next character is an '"'-character (which represents the closing '"'-character)
Use this regex like so: myString.replace("\w*="([^"]*(?="))", "\1"). That will replace the whole Name="myName" with simply myName.
Hope this helps
First I created a DataAttributes class.
DataAttributes.java
public class DataAttributes {
// declare xml attributes of QR code xml response
public static final String
DATA_TAG = "PrintLetterBarcodeData",
UID_ATTR = "uid",
NAME_ATTR = "name",
GENDER_ATTR = "gender",
GNAME_ATTR = "gname",
HOUSE_ATTR = "house",
STREET_ATTR = "street",
LM_ATTR = "lm",
LOC_ATTR = "loc",
VTC_ATTR = "vtc",
PO_ATTR = "po",
DIST_ATTR = "dist",
SUBDIST_ATTR = "subdist",
STATE_ATTR = "state",
PC_ATTR = "pc",
DOB_ATTR = "dob";
}
After QR code is being scanned and stored in a string.
In your activity where you want to display the scanned data, in my case its QRActivity... so I made a method with single argument -> (String scanData) in QRActivity class in QRActivity.java
Inside which the following code is written
Log.d("QR Code",scanData);
XmlPullParserFactory pullParserFactory;
try {
// init the parserfactory
pullParserFactory = XmlPullParserFactory.newInstance();
// get the parser
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(new StringReader(scanData));
// parse the XML
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
Log.d("QR Code","Start document");
} else if(eventType == XmlPullParser.START_TAG && DataAttributes.DATA_TAG.equals(parser.getName())) {
// extract data from tag
//uid
uid = parser.getAttributeValue(null,DataAttributes.UID_ATTR);
//name
name = parser.getAttributeValue(null,DataAttributes.NAME_ATTR);
//gender
gender = parser.getAttributeValue(null,DataAttributes.GENDER_ATTR);
// guardian name
gname = parser.getAttributeValue(null,DataAttributes.GNAME_ATTR);
// house number
house = parser.getAttributeValue(null,DataAttributes.HOUSE_ATTR);
// Street name
street = parser.getAttributeValue(null,DataAttributes.STREET_ATTR);
// landmark
lm = parser.getAttributeValue(null,DataAttributes.LM_ATTR);
// locality
loc = parser.getAttributeValue(null,DataAttributes.LOC_ATTR);
// village town city
vtc = parser.getAttributeValue(null,DataAttributes.VTC_ATTR);
// Post Office
po = parser.getAttributeValue(null,DataAttributes.PO_ATTR);
// district
dist = parser.getAttributeValue(null,DataAttributes.DIST_ATTR);
// sub-division
subdist = parser.getAttributeValue(null,DataAttributes.SUBDIST_ATTR);
// state
state = parser.getAttributeValue(null,DataAttributes.STATE_ATTR);
// Post Code
pc = parser.getAttributeValue(null,DataAttributes.PC_ATTR);
// Date of Birth
dob = parser.getAttributeValue(null,DataAttributes.DOB_ATTR);
} else if(eventType == XmlPullParser.END_TAG) {
Log.d("QR Code","End tag "+parser.getName());
} else if(eventType == XmlPullParser.TEXT) {
Log.d("QR Code","Text "+parser.getText());
}
// update eventType
eventType = parser.next();
}
// display the data on screen
String na = "N/A";
if (uid == null){
tv_uid.setText(na);
}else {
tv_uid.setText(uid);
}
if (name == null){
tv_name.setText(na);
}else {
tv_name.setText(name);
}
if (gender == null){
tv_gender.setText(na);
}else {
tv_gender.setText(gender);
}
if (gname == null){
tv_gName.setText(na);
}else {
tv_gName.setText(gname);
}
if (house == null){
tv_house.setText(na);
}else {
tv_house.setText(house);
}
if (street == null){
tv_street.setText(na);
}else {
tv_street.setText(street);
}
if (lm == null){
tv_lm.setText(na);
}else {
tv_lm.setText(lm);
}
if (loc == null){
tv_loc.setText(na);
}else {
tv_loc.setText(loc);
}
if (vtc == null){
tv_vtc.setText(na);
}else {
tv_vtc.setText(vtc);
}
if (po == null){
tv_po.setText(na);
}else {
tv_po.setText(po);
}
if (dist == null){
tv_dist.setText(na);
}else {
tv_dist.setText(dist);
}
if (subdist == null){
tv_subdist.setText(na);
}else {
tv_subdist.setText(subdist);
}
if (state == null){
tv_state.setText(na);
}else {
tv_state.setText(state);
}
if (pc == null){
tv_pc.setText(na);
}else {
tv_pc.setText(pc);
}
if (dob == null){
tv_dob.setText(na);
}else {
tv_dob.setText(dob);
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The above code is a sample of how I used XMLPullParserFactory to fragment a string into appropriate pieces and then show them separately.
Now you use the method appropriate for your purpose in the Activity. I just showed my way of implementing the XMLPullParserFactory to split the string.

Validation error with ArrayList

I'm attempting to add an ArrayList to an object with a do...while loop. Unfortunately I continue to get a validation error each time I run the program.
Here is the function that I am using to add an ArrayList to the object DVD:
public DVD getNewDVDInfo() {
String title = io.readString("Please enter DVD title");
String releaseDate = io.readString("Please enter Release Date (mm-DD-yyyy)");
LocalDate ld = LocalDate.parse(releaseDate, DateTimeFormatter.ofPattern("mm-DD-yyyy"));
String mpaaRating = io.readString("Please enter MPAA Rating");
String directorName = io.readString("Please enter Director's Name");
String studio = io.readString("Please enter Studio");
boolean hasNext = true;
ArrayList<String> userRating = new ArrayList<>();
String userRatingString = io.readString("Please enter User Rating");
userRating.add(userRatingString);
DVD currentDVD = new DVD(title);
currentDVD.setReleaseDate(ld);
currentDVD.setMpaaRating(mpaaRating);
currentDVD.setDirectorName(directorName);
currentDVD.setStudio(studio);
currentDVD.setUserRating(userRating);
return currentDVD;
}
The validation method:
private void validateDVDData(DVD dvd) throws DVDLibraryDataValidationException {
if (dvd.getTitle() == null || dvd.getTitle().trim().length() == 0
|| dvd.getReleaseDate() == null
|| dvd.getMpaaRating() == null || dvd.getMpaaRating().trim().length() == 0
|| dvd.getDirectorName() == null || dvd.getDirectorName().trim().length() == 0
|| dvd.getStudio() == null || dvd.getStudio().trim().length() == 0
|| dvd.getUserRating()== null || dvd.getUserRating().isEmpty()); {
throw new DVDLibraryDataValidationException("ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name, Studio, User Rating] are required");
}
}
Every time I run the app, the error message is thrown.
Any help would be much appreciated.
To identify your problem you could use a debugger but you could also improve the way of doing the check.
Instead of doing a global error :
ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name,
Studio, User Rating] are required");
it would be more helpful to the user (and also to you for tracing the information) to know where is exactly the problem in the provided values.
In your DVDLibraryDataValidationException class, you could add a List of String field where you add the error field names.
And you could override getMessage() of this class to provide a helpful message indicating the fields with validation error.
Just to give an idea on the way to start :
List<String> errorFields = new ArrayList<>();
if (dvd.getTitle() == null || dvd.getTitle().trim().length() == 0){
errorFields.add("title");
}
if (dvd.getReleaseDate() == null ){
errorFields.add("release date");
}
...
if (!errorFields.isEmpty()){
throw new DVDLibraryDataValidationException("ERROR: All fields [Title, Release Date, MPAA Rating, Director's Name, Studio, User Rating] are required",
errorFields);
}

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 - checking for certain value does not

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...

Categories

Resources