I want to ask you if you know of practical way to display data (maybe in tabular format) coming from a WebService.
I'm really new to j2me, I've just learned how to consume RESTful webservices, now I need to learn how show that data (which comes in json format) to the user.
Basically this is the code I use:
protected String jsonParse(String url) {
StringBuffer stringBuffer = new StringBuffer();
InputStream is = null;
HttpConnection hc = null;
System.out.println(url);
String Results = null;
try {
mProgressString.setText("Connecting...");
hc = (HttpConnection) Connector.open(url, Connector.READ);
hc.setRequestMethod(HttpConnection.GET);
hc.setRequestProperty("User-Agent", "Profile/MIDP-2.1 Configuration/CLDC-1.1");
if (hc.getResponseCode() == HttpConnection.HTTP_OK) {
is = hc.openInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
}
} catch (SecurityException se) {
System.out.println("Security Excepction: " + se);
} catch (NullPointerException npe) {
System.out.println("Null Pointer Excepction: " + npe);
} catch (IOException ioe) {
System.out.println("IO Exception" + ioe);
}
try {
hc.close();
is.close();
} catch (Exception e) {
System.out.println("Error in MostActivePareser Connection close:" + e);
e.printStackTrace();
}
String jsonData = stringBuffer.toString();
try {
JSONArray js = new JSONArray(jsonData);
System.out.println(js.length());
mProgressString.setText("Reading...");
String Results = "";
for (int i = 0; i < js.length(); i++) {
JSONObject jsObj = js.getJSONObject(i);
Results += "-----------------------------------\n";
Results += jsObj.getString("Name") + " \n";
Results += jsObj.getString("Phone") + " \n";
Results += jsObj.getString("Address");
}
} catch (JSONException e1) {
System.out.println("Json Data error:" + e1);
e1.printStackTrace();
} catch (NullPointerException e) {
System.out.println("null error:" + e);
}
return Results;
}
As you can see I only concatenating the results to then show it to the user.But surely there's gotta be better ways to that and here's where I need you help.
How would you display a typical json Array in j2me ?? How do you deal with limitations such as limited memory and small screen sizes when you have to work with a considerable number of results?
As always, any advice or resources you could provide would be greatly appreciated.
Thanks in advance.
P.S. This is the jar I used to work with json.
This link will definitely help you dealing with JSONArray.
To talk about memory limitation,you just try to clean up the resources/data structures that you don't need any more means about UI just keep instance of current screen alive (if possible) no need of other instances in stack.If your array contains many objects that you can't display at a one time (as can cause OOM like issues),then you can think of Pagination.
You can get better idea about Memory Optimization from this must see presentation.
Related
This is a homework assignment where we have to debug and handle exceptions. I setup a try-catch to handle any input that isn't a double and the exception that comes up is caught, but it still prints the error. Here is my code:
import java.util.Scanner;
import java.util.InputMismatchException;
public class Paint1 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
do {
System.out.println("Enter wall height (feet): ");
try {
wallHeight = scnr.nextDouble();
throw new InputMismatchException();
} catch (InputMismatchException exc) {
System.out.println("Invalid input. Please try again.");
wallHeight = scnr.nextDouble();
}
} while (wallHeight <= 0);
...
...
}
}
and this is the output. Note: I used the number thirty spelled out to test the exception for the sake of the assignment.
Enter wall height (feet):
thirty
Invalid input. Please try again.
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Paint1.main(Paint1.java:24)
What am I missing or what do I have that I'm not supposed to?
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
You will have to pass this token by yourself, you can use the next() function to read and pass this token. Since the token was not passed your code was again reading the same token and that's why you were getting InputMismatchException again.
do {
System.out.println("Enter wall height (feet): ");
try {
wallHeight = scnr.nextDouble();
throw new InputMismatchException();
} catch (InputMismatchException exc) {
System.out.println("Invalid input " + scnr.next() + ".Please try again.");
wallHeight = scnr.nextDouble();
}
} while (wallHeight <= 0);
System.out.println("WallHeight: " + wallHeight);
Input:
aaa
10
Output:
Enter wall height (feet):
Invalid input aaa.Please try again.
WallHeight: 10.0
Still, this approach has an issue, What if the second value is invalid? Then it will throw the InputMismatchException, I would suggest to separate out the logic of reading input in a different function and that function should call itself when the input is wrong. Something like:
private Integer findValidIntValue(Integer numberOfChecks){
if(numberOfChecks > MAXIMUM_CHECKS_ALLOWED){
throw new InputMismatchException();
}
try {
wallHeight = scnr.nextDouble();
} catch (InputMismatchException exc) {
System.out.println("Invalid input " + scnr.next() + ".Please try again.");
return findValidIntValue(numberOfChecks + 1);
}
}
i'm trying to upload an image to mysql database using phpmyadmin and despite the program works and stores the rest of the data the image is not stored correctly.
If I upload an image directly in phpmyadmin the image's size in type Blob it's 26.6 KB but if I try to uploading using javafx the image's size it's about 10 B so I think i'm not uploading correctly.
#Override
public void guardarMonstruo(MonstruoDTO monstruo) {
con= ConexionBDA.getInstance().getCon();
try {
if (con != null){
byte[] blob = imagenToByte(monstruo.getImagen());
System.out.println(blob.toString());
statement = con.createStatement();
statement.executeUpdate("INSERT INTO monstruos (Nombre,Habitat,Estado,ColaCercenable,DragonAnciano,DebilidadFuego,DebilidadAgua,Debilidadrayo,DebilidadHielo,DebilidadDraco,ImagenMonstruo) VALUES ('"+monstruo.getNombre()+"'"+","+"'"+monstruo.getHabitat()+"'"+","+"'"+monstruo.getEstado()+"'"+","+"'"+monstruo.getColaCercenable()+"'"+","+"'"+monstruo.getDragonAnciano()+"'"+","+"'"+monstruo.getDebilidadFuego()+"'"+","+"'"+monstruo.getDebilidadAgua()+"'"+","+"'"+monstruo.getDebilidadRayo()+"'"+","+"'"+monstruo.getDebilidadHielo()+"'"+","+"'"+monstruo.getDebilidadDraco()+"'"+","+"'"+blob+"');");
con.close();
statement.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
And the method imagenToByte() is used to pass the image to byte is this:
private byte[] imagenToByte(Image imagen) {
BufferedImage bufferimage = SwingFXUtils.fromFXImage(imagen, null);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
ImageIO.write(bufferimage, "jpg", output );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte [] data = output.toByteArray();
return data;
}
I don't know what i'm doing wrong, could you please help me?
You insert the result of the toString method to the query string which won't result in the desired outcome. Use PreparedStatement and set a Blob parameter instead:
try (PreparedStatement ps = con.prepareStatement("INSERT INTO monstruos (Nombre,Habitat,Estado,ColaCercenable,DragonAnciano,DebilidadFuego,DebilidadAgua,Debilidadrayo,DebilidadHielo,DebilidadDraco,ImagenMonstruo) VALUES (?,?,?,?,?,?,?,?,?,?,?)")) {
ps.setString(1, monstruo.getNombre());
ps.setString(2, monstruo.getHabitat());
ps.setString(3, monstruo.getEstado());
ps.setString(4, monstruo.getColaCercenable());
ps.setString(5, monstruo.getDragonAnciano());
ps.setString(6, monstruo.getDebilidadFuego());
ps.setString(7, monstruo.getDebilidadAgua());
ps.setString(8, monstruo.getDebilidadRayo());
ps.setString(9, monstruo.getDebilidadHielo());
ps.setString(10, monstruo.getDebilidadDraco());
// upload the data, not the toString result of the array
ps.setBlob(11, new SerialBlob(blob));
ps.executeUpdate();
}
I find the best way to save game data in Unity3D Game engine.
At first, I serialize objects using BinaryFormatter.
But I heard this way has some issues and is not suitable for save.
So, What is the best or recommended way for saving game state?
In my case, save format must be byte array.
But I heard this way has some issues and not suitable for save.
That's right. On some devices, there are issues with BinaryFormatter. It gets worse when you update or change the class. Your old settings might be lost since the classes non longer match. Sometimes, you get an exception when reading the saved data due to this.
Also, on iOS, you have to add Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); or you will have problems with BinaryFormatter.
The best way to save is with PlayerPrefs and Json. You can learn how to do that here.
In my case, save format must be byte array
In this case, you can convert it to json then convert the json string to byte array. You can then use File.WriteAllBytes and File.ReadAllBytes to save and read the byte array.
Here is a Generic class that can be used to save data. Almost the-same as this but it does not use PlayerPrefs. It uses file to save the json data.
DataSaver class:
public class DataSaver
{
//Save Data
public static void saveData<T>(T dataToSave, string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Convert To Json then to bytes
string jsonData = JsonUtility.ToJson(dataToSave, true);
byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
}
//Debug.Log(path);
try
{
File.WriteAllBytes(tempPath, jsonByte);
Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
//Load Data
public static T loadData<T>(string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return default(T);
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return default(T);
}
//Load saved Json
byte[] jsonByte = null;
try
{
jsonByte = File.ReadAllBytes(tempPath);
Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
//Convert to json string
string jsonData = Encoding.ASCII.GetString(jsonByte);
//Convert to Object
object resultValue = JsonUtility.FromJson<T>(jsonData);
return (T)Convert.ChangeType(resultValue, typeof(T));
}
public static bool deleteData(string dataFileName)
{
bool success = false;
//Load Data
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return false;
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return false;
}
try
{
File.Delete(tempPath);
Debug.Log("Data deleted from: " + tempPath.Replace("/", "\\"));
success = true;
}
catch (Exception e)
{
Debug.LogWarning("Failed To Delete Data: " + e.Message);
}
return success;
}
}
USAGE:
Example class to Save:
[Serializable]
public class PlayerInfo
{
public List<int> ID = new List<int>();
public List<int> Amounts = new List<int>();
public int life = 0;
public float highScore = 0;
}
Save Data:
PlayerInfo saveData = new PlayerInfo();
saveData.life = 99;
saveData.highScore = 40;
//Save data from PlayerInfo to a file named players
DataSaver.saveData(saveData, "players");
Load Data:
PlayerInfo loadedData = DataSaver.loadData<PlayerInfo>("players");
if (loadedData == null)
{
return;
}
//Display loaded Data
Debug.Log("Life: " + loadedData.life);
Debug.Log("High Score: " + loadedData.highScore);
for (int i = 0; i < loadedData.ID.Count; i++)
{
Debug.Log("ID: " + loadedData.ID[i]);
}
for (int i = 0; i < loadedData.Amounts.Count; i++)
{
Debug.Log("Amounts: " + loadedData.Amounts[i]);
}
Delete Data:
DataSaver.deleteData("players");
I know this post is old, but in case other users also find it while searching for save strategies, remember:
PlayerPrefs is not for storing game state. It is explicitly named "PlayerPrefs" to indicate its use: storing player preferences. It is essentially plain text. It can easily be located, opened, and edited by any player. This may not be a concern for all developers, but it will matter to many whose games are competitive.
Use PlayerPrefs for Options menu settings like volume sliders and graphics settings: things where you don't care that the player can set and change them at will.
Use I/O and serialization for saving game data, or send it to a server as Json. These methods are more secure than PlayerPrefs, even if you encrypt the data before saving.
I find the best way to save game data in Unity3D Game engine.
At first, I serialize objects using BinaryFormatter.
But I heard this way has some issues and is not suitable for save.
So, What is the best or recommended way for saving game state?
In my case, save format must be byte array.
But I heard this way has some issues and not suitable for save.
That's right. On some devices, there are issues with BinaryFormatter. It gets worse when you update or change the class. Your old settings might be lost since the classes non longer match. Sometimes, you get an exception when reading the saved data due to this.
Also, on iOS, you have to add Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); or you will have problems with BinaryFormatter.
The best way to save is with PlayerPrefs and Json. You can learn how to do that here.
In my case, save format must be byte array
In this case, you can convert it to json then convert the json string to byte array. You can then use File.WriteAllBytes and File.ReadAllBytes to save and read the byte array.
Here is a Generic class that can be used to save data. Almost the-same as this but it does not use PlayerPrefs. It uses file to save the json data.
DataSaver class:
public class DataSaver
{
//Save Data
public static void saveData<T>(T dataToSave, string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Convert To Json then to bytes
string jsonData = JsonUtility.ToJson(dataToSave, true);
byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
}
//Debug.Log(path);
try
{
File.WriteAllBytes(tempPath, jsonByte);
Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
//Load Data
public static T loadData<T>(string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return default(T);
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return default(T);
}
//Load saved Json
byte[] jsonByte = null;
try
{
jsonByte = File.ReadAllBytes(tempPath);
Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
//Convert to json string
string jsonData = Encoding.ASCII.GetString(jsonByte);
//Convert to Object
object resultValue = JsonUtility.FromJson<T>(jsonData);
return (T)Convert.ChangeType(resultValue, typeof(T));
}
public static bool deleteData(string dataFileName)
{
bool success = false;
//Load Data
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return false;
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return false;
}
try
{
File.Delete(tempPath);
Debug.Log("Data deleted from: " + tempPath.Replace("/", "\\"));
success = true;
}
catch (Exception e)
{
Debug.LogWarning("Failed To Delete Data: " + e.Message);
}
return success;
}
}
USAGE:
Example class to Save:
[Serializable]
public class PlayerInfo
{
public List<int> ID = new List<int>();
public List<int> Amounts = new List<int>();
public int life = 0;
public float highScore = 0;
}
Save Data:
PlayerInfo saveData = new PlayerInfo();
saveData.life = 99;
saveData.highScore = 40;
//Save data from PlayerInfo to a file named players
DataSaver.saveData(saveData, "players");
Load Data:
PlayerInfo loadedData = DataSaver.loadData<PlayerInfo>("players");
if (loadedData == null)
{
return;
}
//Display loaded Data
Debug.Log("Life: " + loadedData.life);
Debug.Log("High Score: " + loadedData.highScore);
for (int i = 0; i < loadedData.ID.Count; i++)
{
Debug.Log("ID: " + loadedData.ID[i]);
}
for (int i = 0; i < loadedData.Amounts.Count; i++)
{
Debug.Log("Amounts: " + loadedData.Amounts[i]);
}
Delete Data:
DataSaver.deleteData("players");
I know this post is old, but in case other users also find it while searching for save strategies, remember:
PlayerPrefs is not for storing game state. It is explicitly named "PlayerPrefs" to indicate its use: storing player preferences. It is essentially plain text. It can easily be located, opened, and edited by any player. This may not be a concern for all developers, but it will matter to many whose games are competitive.
Use PlayerPrefs for Options menu settings like volume sliders and graphics settings: things where you don't care that the player can set and change them at will.
Use I/O and serialization for saving game data, or send it to a server as Json. These methods are more secure than PlayerPrefs, even if you encrypt the data before saving.
I have to process an xml against an xslt with result-document that create many xml.
As suggested here:
Catch output stream of xsl result-document
I wrote my personal URI Resolver:
public class CustomOutputURIResolver implements OutputURIResolver{
private File directoryOut;
public CustomOutputURIResolver(File directoryOut) {
super();
this.directoryOut = directoryOut;
}
public void close(Result arg0) throws TransformerException {
}
public Result resolve(String href, String base) throws TransformerException {
FileOutputStream fout = null;
try {
File f = new File(directoryOut.getAbsolutePath() + File.separator + href + File.separator + href + ".xml");
f.getParentFile().mkdirs();
fout = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new StreamResult(fout);
}
}
that get the output directory and then saves here the files.
But then when I tested it in a junit I had some problems in the clean-up phase, when trying to delete the created files and noticed that the FileOutputStream fout is not well handled.
Trying to solve the problem gave me some thoughts:
First I came out with this idea:
public class CustomOutputURIResolver implements OutputURIResolver{
private File directoryOut;
private FileOutputStream fout
public CustomOutputURIResolver(File directoryOut) {
super();
this.directoryOut = directoryOut;
this.fout = null;
}
public void close(Result arg0) throws TransformerException {
try {
if (null != fout) {
fout.flush();
fout.close();
fout = null;
}
} catch (Exception e) {}
}
public Result resolve(String href, String base) throws TransformerException {
try {
if (null != fout) {
fout.flush();
fout.close();
}
} catch (Exception e) {}
fout = null;
try {
File f = new File(directoryOut.getAbsolutePath() + File.separator + href + File.separator + href + ".xml");
f.getParentFile().mkdirs();
fout = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new StreamResult(fout);
}
}
So the fileOutputStream is closed anytime another one is opened.
But:
1) I don't like this solution very much
2) what if this function is called in a multithread process? (I'm not very skilled about Saxon parsing, so i really don't know..)
3) Is there a chance to create and handle one FileOutputStream for each resolve ?
The reason close() takes a Result argument is so that you can identify which stream to close. Why not:
public void close(Result arg0) throws TransformerException {
try {
if (arg0 instanceof StreamResult) {
OutputStream os = ((StreamResult)arg0).getOutputStream();
os.flush();
os.close();
}
} catch (Exception e) {}
}
From Saxon-EE 9.5, xsl:result-document executes in a new thread, so it's very important that the OutputURIResolver should be thread-safe. Because of this change, from 9.5 an OutputURIResolver must implement an additional method getInstance() which makes it easier to manage state: if your newInstance() method actually creates a new instance, then there will be one instance of the OutputURIResolver for each result document being processed, and it can hold the output stream and close it when requested.