I'm currently trying to write a program that get a stringified json object from steam and uses the object to determine if I can buy an item on the steam market or not.
It works, however I seem to be getting massive memory leaks and I have no idea how to solve this problem as I'm a beginner programmer. Here is the code:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class SteamMarketAlert {
@SuppressWarnings("unused")
private JAlertWindow alert;
private URL jsonUrl;
private float walletValue;
private boolean itemBuyable;
public SteamMarketAlert(URL itemUrl, float walletValue)
{
this.itemBuyable = false;
this.jsonUrl = getJSONurl(itemUrl);
this.walletValue = walletValue;
}
private URL getJSONurl(URL itemUrl)
{
String jsonString = itemUrl.toString();
String firstPart = jsonString.substring(0, jsonString.indexOf("market/") + "market/".length());
String appid = jsonString.split("/")[5];
String marketHashName = jsonString.split("/")[6];
String secondPart = "priceoverview/?currency=2&appid=" + appid + "&market_hash_name=" + marketHashName;
try {
return new URL(firstPart + secondPart);
} catch (MalformedURLException e) {
System.err.println("Failed to create json url");
return null;
}
}
public void checkMarket()
{
Thread thread = new Thread(){
@Override
public void run(){
try {
while(!itemBuyable)
{
sleep(5000);
if(isBuyable(getPagehtml()))
itemBuyable = true;
}
alert = new JAlertWindow();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private boolean isBuyable(String pagehtml)
{
int firstIndex = pagehtml.indexOf(";") +1;
float marketValue = Float.parseFloat(pagehtml.substring(firstIndex, firstIndex + pagehtml.substring(firstIndex, pagehtml.length()).indexOf("\"")));
return (marketValue <= walletValue)? true:false;
}
private String getPagehtml(){
try(Scanner scanner = new Scanner(jsonUrl.openConnection().getInputStream())) {
scanner.useDelimiter("\\Z");
return scanner.next();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args)
{
try {
float walletValue = 82.64f;
URL itemUrl = new URL("http://steamcommunity.com/market/listings/730/StatTrak%E2%84%A2%20P90%20%7C%20Asiimov%20%28Factory%20New%29");
SteamMarketAlert sma = new SteamMarketAlert(itemUrl,walletValue);
sma.checkMarket();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
I've narrowed the problem down to the checkMarket() method. However, I can't seem to figure out what is going on. Can you please point out how I can fix this (and possibly point out all the flaws in my code), Note the JAlertWindow object just displays a JFrame with "CAN BUY" on it - nothing special.
edit: I updated the code since posting and users informed me that try-with-resource blocks existed. Thank you to everyone who has helped me understand how java garbage collection works. :)!