String statement returning null from switch statement - java

I am currently working on an Android application that allows you to watch streaming video in a VideoView. I have a method for allowing you to select one of four streams via a switch statement. That is working correctly and the code for that is as follows:
public void playStream(int position) {
switch (position) {
case 0:
streamOn = true;
streamPos = 0;
logString = "M";
posSelected = "0";
break;
case 1:
streamOn = true;
streamPos = 1;
logString = "J";
posSelected = "1";
break;
case 2:
streamOn = true;
streamPos = 2;
logString = "B";
posSelected = "2";
break;
case 3:
streamOn = true;
streamPos = 3;
logString = "N";
posSelected = "3";
break;
default:
break;
}
checkStreamLink(position);
Log.wtf(logString, posSelected);
Log.wtf(logString, streamURL);
}
What is not working correctly is that in this method for selecting the stream, I have a call to another method ( checkStreamLink(); ) that runs a thread. Depending on which stream you have selected, the thread will call another method that opens up a webpage, reads a line of text, and then sets that text to a String streamURL. The code for those two methods is as follows:
public void checkStreamLink(final int position) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
switch (position) {
case 0:
streamURL = getStreamLink("LINK 0 GOES HERE");
break;
case 1:
streamURL = getStreamLink("LINK 1 GOES HERE");
break;
case 2:
streamURL = getStreamLink("LINK 2 GOES HERE");
break;
case 3:
streamURL = getStreamLink("LINK 3 GOES HERE");
break;
default:
break;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
public String getStreamLink (String textSource) {
URL streamURL;
String errorParsingURL = "ERROR PARSING URL";
try {
streamURL = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(streamURL.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
return stringText;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return errorParsingURL;
}
The issue I'm having is that the String streamURL is returning null on its first use as evidenced by the Log statements I have included. Each time you select a stream after that, the String streamURL returns the text that you should have received the previous time you select a stream. I cannot seem to figure out why this is happening and I would appreciate any assistance.

You are getting a null because getStreamLink is returning its value after you have already printed the result. Print the result log messages at the end of the getStreamLink method to see the actual value which is being returned, and call any additional functionality at that point as well.

Related

Drools Unterminated Collection Element Error

I have when statement that goes from an if statement to the else statement:
rule "rule"
ruleflow-group "ruleFlow"
when
$block : Block()
$inst : BlockInstitution(blockInstitutionCategory!=null) from $block.getInstitution()
$categorycode : InstitutionCategory(Constants.INSTITUTION_CATEGORY_CODE.equals(institutionCategoryCode)) from $inst.getInstitutionCategory()
$list : BlockInstitution(Constants.validNonList not contains dealCode) from $block.getInstitution()
then
Service $service = new Service();
try {
JsonObject enquiry =
$service.execute($block.getTransaction().getNumber()).get();
if (enquiry.isEmpty()) {
$block.getBusinessValidationResult().add(ValidationResult.NOT_FOUND);
$block.getMsg().setStatusText(Constants.NOT_FOUND);
}
else {
String numberFromService = statusEnquiry.getString(Constants.NUMBER);
String cardExpiryFromService =
enquiry.getString(Constants.EXPIRY_DATE);
String paymentRequestorIdentifier =
enquiry.getString(Constants.IDENTIFIER);
String paymentExpiryDate = enquiry.getString(Constants.EXPIRY_DATE);
String statusText = enquiry.getString(Constants.STATUS_TEXT);
String providerIdentifier =
enquiry.getString(Constants.PROVIDER_IDENTIFIER);
if (Objects.nonNull(paymentExpiryDate)) {
paymentExpiryDate =
EncryptionUtilFactory.getInstance().decryptData(paymentExpiryDate);
if (paymentExpiryDate.length() == 4) {
paymentExpiryDate =
paymentExpiryDate.substring(2, 4) + paymentExpiryDate.substring(0, 2);
}
paymentExpiryDate =
EncryptionUtilFactory.getInstance().encryptData(paymentExpiryDate);
}
if (Objects.nonNull(cardExpiryFromService)) {
cardExpiryFromService =
EncryptionUtilFactory.getInstance().decryptData(cardExpiryFromService);
if (cardExpiryFromService.length() == 4) {
cardExpiryFromService =
cardExpiryFromService.substring(2, 4) + cardExpiryFromService.substring(0, 2);
}
cardExpiryFromService =
EncryptionUtilFactory.getInstance().encryptData(cardExpiryFromService);
}
$block.getTransaction().setServiceNumber(numberFromService);
$block.getTransaction().setServiceAccountExpirationDate(cardExpiryFromService);
$block.getTransaction().setPaymentExpiryDate(paymentExpiryDate);
$block
.getTransaction()
.setFlag(Constants.ID_SET.contains(providerIdentifier));
$block.getTransaction().setProviderIdentifier(providerIdentifier);
String text = $block.getTransaction().getPrimaryAccountNumber();
$block.getTransaction().setText(text);
$block.getTransaction().setStatusText(statusText);
$block
.getTransaction()
.setPaymentRequestorIdentifier(paymentRequestorIdentifier);
if (!Constants.STATUS.equals(statusText)) {
switch (statusText) {
case Constants.INACTIVE_STATUS:
$block.getBusinessValidationResult().add(ValidationResult.INACTIVE);
break;
case Constants.CANCELLED_STATUS:
$block.getBusinessValidationResult().add(ValidationResult.CANCELLED);
break;
case Constants.SUSPENDED_STATUS:
$block.getBusinessValidationResult().add(ValidationResult.SUSPENDED);
break;
default:
break;
}
}
}
} catch (Exception ex) {
$block.getBusinessValidationResult().add(ValidationResult.CALL_FAILED);
$block.getTransaction().setStatusText(Constants.NOT_FOUND);
}
end
ERROR:
[Error: unterminated collection element]
[Near : {... _FOUND); } else { String numberFr ....}]
As the code goes from the if block to the else block it gives me an error: "Unterminated Collection Element".
Is there anything you see that indicates what's wrong. I can't find anything on the Internet that discusses this error. I've found "Unterminated String Element", but nothing on collection elements.

Java try/catch method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm new to Java and my function has a lot of try/catch blocks that I would like to clean up. I wanted to take each section and put it in a separate private helper method and only call a few functions within the main function, but when I do so, I get a java.util.NoSuchElementException for Scanner.
Here is the original function. Any help would be much appreciated.
public void playGame(List<Card> deck, FreecellOperations<Card> model, int numCascades,
int numOpens, boolean shuffle) {
try {
Scanner scan = new Scanner(rd);
try {
Objects.requireNonNull(model);
Objects.requireNonNull(deck);
} catch (NullPointerException npe) {
throw new IllegalArgumentException("Cannot start game with null parameters.");
}
try {
model.startGame(deck, numCascades, numOpens, shuffle);
} catch (IllegalArgumentException iae) {
ap.append("Could not start game. " + iae.getMessage());
return;
}
ap.append(model.getGameState() + "\n");
while (!model.isGameOver()) {
String source = scan.next();
if (source.substring(0, 1).equals("q") || source.substring(0, 1).equals("Q")) {
ap.append("Game quit prematurely.");
return;
}
String cardIndex = scan.next();
if (cardIndex.substring(0, 1).equals("q") || cardIndex.substring(0, 1).equals("Q")) {
ap.append("Game quit prematurely.");
return;
}
String destination = scan.next();
if (destination.substring(0, 1).equals("q") || destination.substring(0, 1).equals("Q")) {
ap.append("Game quit prematurely.");
return;
}
int pileNumber = 0;
PileType sourceType = null;
boolean isValidSource = false;
while (!isValidSource) {
try {
switch (source.charAt(0)) {
case 'F':
sourceType = PileType.FOUNDATION;
pileNumber = this.validMoveCheck(source, 4);
isValidSource = true;
break;
case 'O':
sourceType = PileType.OPEN;
pileNumber = this.validMoveCheck(source, numOpens);
isValidSource = true;
break;
case 'C':
sourceType = PileType.CASCADE;
pileNumber = this.validMoveCheck(source, numCascades);
isValidSource = true;
break;
default:
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException iae) {
ap.append("Invalid source pile. Try again.\n");
source = scan.next();
if (source.equals("q") || source.equals("Q")) {
ap.append("Game quit prematurely.");
return;
}
}
}
int cardNum = 0;
boolean isValidCard = false;
while (!isValidCard) {
try {
cardNum = Integer.parseInt(cardIndex);
isValidCard = true;
} catch (NumberFormatException nfe) {
ap.append("Invalid card number. Try again.\n");
cardIndex = scan.next();
if (cardIndex.equals("Q") || cardIndex.equals("q")) {
ap.append("Game quit prematurely.");
return;
}
}
}
PileType destType = null;
int destPileNum = 0;
boolean isValidDest = false;
while (!isValidDest) {
try {
switch (destination.charAt(0)) {
case 'F':
destType = PileType.FOUNDATION;
destPileNum = this.validMoveCheck(destination, 4);
isValidDest = true;
break;
case 'C':
destType = PileType.CASCADE;
destPileNum = this.validMoveCheck(destination, numCascades);
isValidDest = true;
break;
case 'O':
destType = PileType.OPEN;
destPileNum = this.validMoveCheck(destination, 4);
isValidDest = true;
break;
default:
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException iae) {
ap.append("Invalid destination pile. Try again.\n");
destination = scan.next();
if (destination.equals("q") || destination.equals("Q")) {
ap.append("Game quit prematurely.");
return;
}
}
}
try {
model.move(sourceType, (pileNumber - 1), (cardNum - 1), destType, (destPileNum - 1));
ap.append(model.getGameState() + "\n");
} catch (IllegalArgumentException iae) {
ap.append("Invalid move. Try again. " + iae.getMessage() + "\n");
}
}
ap.append("Game over.");
} catch (IOException ioe) {
return;
}
}
First, In order not to get java.util.NoSuchElementException, you need to check if the next line exists using hasNextLine().
Add that check in your while loop:
while (!model.isGameOver() && scan.hasNextLine()) {
...
}
Second, you got pretty good code styling tips in the other comments here, I suggest you to take them :)
A few comments:
First, you can replace a lot of these try/catch blocks with simple if statements (or eliminate them altogether).
For example:
default:
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException iae) {
ap.append("Invalid destination pile. Try again.\n");
destination = scan.next();
if (destination.equals("q") || destination.equals("Q")) {
ap.append("Game quit prematurely.");
return;
}
}
Why not just do:
default:
ap.append("Invalid destination pile. Try again.\n");
destination = scan.next();
if (destination.equals("q") || destination.equals("Q")) {
ap.append("Game quit prematurely.");
return;
}
break;
or something like that instead? Why bother with the exception?
Also, this logic is incorrect:
cardNum = Integer.parseInt(cardIndex);
isValidCard = true;
The fact that it's an integer doesn't prove that it's a valid card. What if someone entered 5,321? Clearly, that is an int, but it's not an actual card. Also, see here (as well as its duplicates) for ways to encapsulate this.

print out from switch statement java

here is a piece of code:
class Main {
public static void main(String[] args) {
try {
CLI.parse (args, new String[0]);
InputStream inputStream = args.length == 0 ?
System.in : new java.io.FileInputStream(CLI.infile);
ANTLRInputStream antlrIOS = new ANTLRInputStream(inputStream);
if (CLI.target == CLI.SCAN || CLI.target == CLI.DEFAULT)
{
DecafScanner lexer = new DecafScanner(antlrIOS);
Token token;
boolean done = false;
while (!done)
{
try
{
for (token=lexer.nextToken();
token.getType()!=Token.EOF; token=lexer.nextToken())
{
String type = "";
String text = token.getText();
switch (token.getType())
{
case DecafScanner.ID:
type = " CHARLITERAL";
break;
}
System.out.println (token.getLine() + type + " " + text);
}
done = true;
} catch(Exception e) {
// print the error:
System.out.println(CLI.infile+" "+e);
}
}
}
else if (CLI.target == CLI.PARSE)
{
DecafScanner lexer = new DecafScanner(antlrIOS);
CommonTokenStream tokens = new CommonTokenStream(lexer);
DecafParser parser = new DecafParser (tokens);
parser.program();
}
} catch(Exception e) {
// print the error:
System.out.println(CLI.infile+" "+e);
}
}
}
It prints out as it is but somehow it does not print the type out only the default value of it which is an empty string. How can I make it to print out from the switch statement?
Thanks!
Try debugging.
Try printing the value from within the switch section, to see if you ever get into it.
Try replacing the switch with a simple "==" to see if you ever get "token.getType() == DecafScanner.ID"
General suggestion - move the definition of "type" and "next" outside the loop to avoid recreating them again and again.

Sample OSLC code with a "where" clause

Could anyone please provide sample OSLC code with a where clause for the service class?
I have just started using OSLC recently.
Here is the code that I have tried (does't work):
#GET
#Produces({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON})
public Project[] getChangeRequests(#QueryParam("oslc.where") final String where,
#QueryParam("oslc.prefix") final String prefix)
{
final List< Project> results = new ArrayList<Project>();
Map<String, String> prefixMap;
try
{
QueryUtils.parseSearchTerms(where);
prefixMap = QueryUtils.parsePrefixes(prefix);
WhereClause whereClause = QueryUtils.parseWhere(where, prefixMap);
}
catch (ParseException e)
{
e.printStackTrace();
}
final Project[] changeRequests = Persistence.getChangeRequestsForProject();
for (final Project changeRequest : changeRequests)
{
changeRequest.setServiceProvider(ServiceProviderSingleton.getServiceProviderURI());
results.add(changeRequest);
}
return results.toArray(new Project[results.size()]);
}
I just thought I will post a working piece of code. Here it is:
prefixMap = QueryUtils.parsePrefixes(prefix);
WhereClause whereClause = QueryUtils.parseWhere(where, prefixMap);
PName property = null;
String value ="";
for (SimpleTerm term : whereClause.children())
{
ComparisonTerm comparison = (ComparisonTerm)term;
String operator;
switch (comparison.operator())
{
case EQUALS:
operator = "equals";
break;
case NOT_EQUALS:
operator = "notequals";
break;
case LESS_THAN:
operator = "lessthan";
break;
case LESS_EQUALS:
operator = "lessthaneq";
break;
case GREATER_THAN:
operator = "greaterthan";
break;
default:
case GREATER_EQUALS:
operator = "greaterhaneq";
break;
}
property = comparison.property();
Value operand = comparison.operand();
value = operand.toString();
switch (operand.type())
{
case STRING:
case URI_REF:
value = value.substring(1, value.length() - 1);
break;
case BOOLEAN:
case DECIMAL:
break;
default:
throw new WebApplicationException
(new UnsupportedOperationException("Unsupported oslc.where comparison operand: " + value),Status.BAD_REQUEST);
}
}
String compareString=property.toString().substring(property.toString().indexOf(":")+1);
String val="get" + compareString.substring(0,1).toUpperCase() +compareString.substring(1);
final Project[] changeRequests = Persistence.getChangeRequestsForProject();
for (final Project changeRequest : changeRequests)
{
changeRequest.setServiceProvider(ServiceProviderSingleton.getServiceProviderURI());
Method m=changeRequest.getClass().getMethod(val, null);
if((m.invoke(changeRequest).toString().equalsIgnoreCase(value)))
{
results.add(changeRequest);
}
}

Android: How to parse HTML Table into ListView?

Hello i want to parse a HTML Table into a Android ListView but i don't know where to start. The Table has a lot of information. Could someone help me to start with this?
Thanks in advance!
The HTML Table: http://intranet.staring.nl/toepassingen/rooster/lochem/2W2/2012090320120909/2W01533.htm (Just click view source).
You will first need to parse the HTML table into a data structure, and then use ListView to display that information. Try using the JSoup library to do the HTML parsing: http://jsoup.org/cookbook/introduction/parsing-a-document
I don't know if you already got your answer here but I did the same with the link you suggest, I will post my code here but it is still very messy and don't apply for the newest timetable(9th hour)
Im using HTML Cleaner library for parsing the html:
try {
HtmlCleaner hc = new HtmlCleaner();
CleanerProperties cp = hc.getProperties();
cp.setAllowHtmlInsideAttributes(true);
cp.setAllowMultiWordAttributes(true);
cp.setRecognizeUnicodeChars(true);
cp.setOmitComments(true);
String loc = sp.getString( Constants.pref_locatie , "" );
String per = sp.getString( Constants.pref_persoon , "" );
String oob = sp.getString( Constants.pref_onderofboven , "" );
int counteruurmax;
int[] pauze;
if (oob.contains("onder")){
pauze = Constants.pauzeo;
} else if (oob.contains("boven")) {
pauze = Constants.pauzeb;
} else {
return false;
}
String url = "";
if (loc.contains("lochem")) {
url += Constants.RoosterLochem;
url += t.getDatum();
url += "/";
url += per;
counteruurmax = 11;
} else if (loc.contains("herenlaan")) {
url += Constants.RoosterHerenlaan;
url += per;
counteruurmax = 13;
} else if (loc.contains("beukenlaan")) {
url += Constants.RoosterBeukenlaan;
url += per;
counteruurmax = 11;
} else {
return false;
}
String htmlcode = t.getHtml(url);
TagNode html = hc.clean(htmlcode);
Document doc = new DomSerializer(cp, true).createDOM(html);
XPath xp = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xp.evaluate(Constants.XPathRooster, doc, XPathConstants.NODESET);
int counteruur = 1;
int counterdag = 1;
int decreaser = 0;
Boolean isPauze = false;
RoosterItems RItems = new RoosterItems();
RoosterItem RItem = null;
for (int i = 0; i < nl.getLength(); i++){
if ((counteruur == pauze[0]) || (counteruur == pauze[1]) || (counteruur == pauze[2])) {
isPauze = true;
decreaser++;
}
if (!isPauze) {
RItem = new RoosterItem();
switch (counterdag){
case 1:
RItem.setDag("ma");
break;
case 2:
RItem.setDag("di");
break;
case 3:
RItem.setDag("wo");
break;
case 4:
RItem.setDag("do");
break;
case 5:
RItem.setDag("vr");
break;
}
Node n = nl.item(i);
String content = n.getTextContent();
if (content.length() > 1) {
RItem.setUur(""+(counteruur-decreaser));
NodeList t1 = n.getChildNodes();
NodeList t2 = t1.item(0).getChildNodes();
NodeList t3 = t2.item(0).getChildNodes();
for (int j = 0; j < t3.getLength(); j++) {
Node temp = t3.item(j);
if (t3.getLength() == 3) {
switch (j) {
case 0:
RItem.setLes(""+temp.getTextContent());
break;
case 1:
RItem.setLokaal(""+temp.getTextContent());
break;
case 2:
RItem.setDocent(""+temp.getTextContent());
break;
default:
return false;
}
} else if (t3.getLength() == 4) {
switch (j) {
case 0:
break;
case 1:
RItem.setLes("tts. " + temp.getTextContent());
break;
case 2:
RItem.setLokaal(""+temp.getTextContent());
break;
case 3:
RItem.setDocent(""+temp.getTextContent());
break;
default:
return false;
}
} else if (t3.getLength() == 1) {
RItem.setLes(""+temp.getTextContent());
} else {
return false;
}
}
} else {
RItem.setUur("" + (counteruur-decreaser));
RItem.setLokaal("Vrij");
}
RItems.add(RItem);
}
if (counteruur == counteruurmax) { counteruur = 0; counterdag++; decreaser = 0;}
counteruur++;
isPauze = false;
}
if (RItems.size() > 0) {
mSQL = new RoosterSQLAdapter(mContext);
mSQL.openToWrite();
mSQL.deleteAll();
for (int j = 0; j < RItems.size(); j++) {
RoosterItem insert = RItems.get(j);
mSQL.insert(insert.getDag(), insert.getUur(), insert.getLes(), insert.getLokaal(), insert.getDocent());
}
if (mSQL != null) mSQL.close();
}
return true;
} catch (ParserConfigurationException e) {
e.printStackTrace();
return false;
} catch (XPathExpressionException e) {
e.printStackTrace();
return false;
}
There are a few constants but I think you can guess them yourself;) and otherwise you know how to ask me for them:)
The RoosterItem class will hold all variables of an hour, and the RoosterItems will hold more than one RoosterItem
Good Luck!
So far i think JSoup is one of the best way to extract or manipulate the HTML.....
See this link :
http://jsoup.org/
But somehow.... this did't worked in my case, so i converted the entire HTML code into String, then parsed it.....

Categories