I am developing a project which involves JSON manipulation in Java using JSON API. There are many places where I need to read values from JSON file. The API provides checked exceptions for the same. Everytime I use the API to read JSON values, I am forced to write try catch block. As a result, there is a large number of try catch blocks. It makes the code look messy.
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
}
catch(Exception e) {
System.out.println("File Not found");
}
try {
while((line = read.readLine() ) != null) {
Content = Content+line;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
ResponseArr = new JSONArray( Content );
} catch (JSONException e) {
e.printStackTrace();
}
try {
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
}
try {
StoreResponse = ResponseArr.getJSONObject(0).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
}
Is there any way to avoid this ?A single try catch block would not suffice and the statements are not dependent. Each read statement requires a separate try catch block as I have to log the details of places while catching the exception. Can I invoke a common method whenever I have a code to read JSON data, like sending the code as a paramater to a method which would take care of the exception handling or some other way round ?
Since (all?) the subsequent statements are dependent on the previous it makes no sense having that many try/catch blocks. I would rather put the code inside one try/catch and handle the exceptions by type
Pseudo-code:
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (JSONException e) {
e.printStackTrace();
} catch(FileNotFoundException)
System.out.println("File Not found");
}
// and so on
As some are suggesting, you might want to let all these exceptions bubble up (not catching them) since you're not doing anything meaningful when catching them. However, I think that depends on the calling context.
If you are handling all exceptions in the same way, why not combine them in one try/ catch clause
for example like this :
try {
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
} catch (Exception e) {
e.printStackTrace();
}
Try like this
String Content = "";
try {
read = new BufferedReader(new FileReader("Data.json"));
while((line = read.readLine() ) != null) {
Content = Content+line;
}
ResponseArr = new JSONArray( Content );
ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
catch(Exception e) {
System.out.println("File Not found");
}
Related
I am trying to get all the mac and IP from my android using the following code. But the following code only works in java. I want to use it in kotlin so I tried java to kotlin converter. But it didn't work. could anyone tell me how the following part of the code will be used in kotlin:
listNote.clear();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ip = splitted[0];
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
Node thisNode = new Node(ip, mac);
listNote.add(thisNode);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Auto conversion does not handle your while loop since "Assignments are not expression".
You can work around it by using built-in Readers extension function forEachLine, in which case each line is passed as the only argument to the lambda expression as it:
var bufferedReader: BufferedReader? = null
try {
bufferedReader = BufferedReader(FileReader("/proc/net/arp"))
bufferedReader.forEachLine {
val splitted = it.split(" +".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (splitted.size >= 4) {
val ip = splitted[0]
val mac = splitted[3]
if (mac.matches("..:..:..:..:..:..".toRegex())) {
listNote.add(Node(ip, mac))
}
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
bufferedReader?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
You can also remove FileNotFoundException since it's a subclass of IOException, and catch block is the same.
I need to pass some Bitmaps from one activity to another, and, since the size limit of the Bundle won't let me pass these images (even using a byte array*), I thought that I could use a getter method between these Activities.
-But, since I'm still not a master in Android (Java), I don't know if that would make any difference, and, if it does, what should I watch out for when using it.
the byte array did reduce the total size(at about 60%), but it still wasn't enough
scaling down is a way out, but just in case any other solution works
save your object in a file
private void saveDataToFile() {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = getContext().openFileOutput("fileName", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(yourObject); //which data u want to save
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Retrieve the object from another activity
private void getDataFromFile() {
FileInputStream fileInputStream = null;
try {
fileInputStream = getContext().openFileInput("fileName");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException |NullPointerException e) {
e.printStackTrace();
}
try {
yourObject = (ObjectClass) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Pass through Uri by writing getter method in POJO class
If you want to use getter setter, just create URI of your bitmap and pass to setter method in POJO class and then retrieve using getter method of POJO class.
I have a program that needs to load data at launch. The data comes from a serialized object. I have a method loadData(), which is called upon construction of the Data class. Sometimes, (I.e. after a loss of saveData, or on first program launch on a new system), the file can be empty. (The file will exist though, the method ensures that).
When I try to run the program, I recieve an EOFException. So, in the method, I try to catch it, and just print a line to the console explaining what happened and return to the caller of the method. (so, upon return, the program will think loadData() is complete and has returned. However, it still crashes throwing the exception without printing a line to the console or anything. It is like it is totally ignoring the catch I have in place.
CODE:
protected void loadData()
{
// Gets/creates file object.
saveFileObject = new File("savedata.ser");
if(!saveFileObject.exists())
{
try
{
saveFileObject.createNewFile();
}
catch(IOException e)
{
System.out.println("Uh oh...");
e.printStackTrace();
}
}
// Create file input stream
try
{
fileIn = new FileInputStream(saveFileObject);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
// Create object input stream
try
{
inputStream = new ObjectInputStream(fileIn);
}
catch(IOException e)
{
e.printStackTrace();
}
// Try to deserialize
try
{
parts = (ArrayList<Part>)inputStream.readObject();
}
catch(EOFException e)
{
System.out.println("EOFException thrown! Attempting to recover!");
return;
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
// close input stream
try
{
inputStream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Any help please?
Try writing your code like :
protected void loadData() {
// Gets/creates file object.
saveFileObject = new File("savedata.ser");
try {
if (!saveFileObject.exists()) {
saveFileObject.createNewFile();
}
// Create file input stream
fileIn = new FileInputStream(saveFileObject);
// Create object input stream
inputStream = new ObjectInputStream(fileIn);
// Try to deserialize
parts = (ArrayList<Part>) inputStream.readObject();
// close input stream
inputStream.close();
} catch (EOFException e) {
System.out.println("EOFException thrown! Attempting to recover!");
} catch (IOException e) {
System.out.println("Uh oh...");
e.printStackTrace();
}
}
Also note that EOFException is a sub-class of IOException
How about making one try and then making catches respectively like here?
I'm looking for a place where are objects after serialization ? I would like to put serialized objects(created in another app) to my android project and then only load this files in my game. The problem is that I don't know where do I have to put this objects ? and even if I save object from android app it never saves in my project folder. My load and save functions for objects
public static void save(Context context, Map obj, String nazwa)
{
FileOutputStream str = null;
ObjectOutputStream objStr = null;
try {
str = context.openFileOutput(nazwa, Context.MODE_PRIVATE);
objStr = new ObjectOutputStream(str);
objStr.writeObject(obj);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (objStr != null) objStr.close();
} catch (IOException e) {}
try
{
if (str != null) str.close();
} catch (IOException e) {}
}
}
public static Map load(Context context, String nameFile)
{
Map obj = null;
FileInputStream str_w = null;
ObjectInputStream obj_w = null;
try
{
str_w = context.openFileInput(nameFile);
obj_w = new ObjectInputStream(str_w);
obj = (Map) obj_w.readObject();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
try
{
if (obj_w != null) obj_w.close();
} catch (IOException e) {}
try
{
if (str_w != null) str_w.close();
} catch (IOException e) {}
}
return obj;
}
If I copy my object file to /levels/ and use
final Map map2 = MapManager.load(this, "/levels/map1.lvl");
or
final Map map2 = MapManager.load(this, "levels/map1.lvl");
it never works
How should I do it ?
You're storing them as app private files (Context.MODE_PRIVATE) to a folder only the app has access to, so no other application will be able to access them.
I think the easiest way to store them so they can be shared between apps is to store them to the sdcard using:
Environment.getExternalStorageDir();
Be aware to store them as globally readable.
I was trying to use this code below to run a native and i get a classnotfoundexception for android.os.exec in Class execClass = Class.forName("android.os.Exec")..any idea y?
try {
// android.os.Exec is not included in android.jar so we need to use reflection.
Class<?> execClass = Class.forName("android.os.Exec");
Method createSubprocess = execClass.getMethod("createSubprocess",
String.class, String.class, String.class, int[].class);
Method waitFor = execClass.getMethod("waitFor", int.class);
// Executes the command.
// NOTE: createSubprocess() is asynchronous.
int[] pid = new int[1];
FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(
null, "/system/bin/ls", "/sdcard", null, pid);
// Reads stdout.
// NOTE: You can write to stdin of the command using new FileOutputStream(fd).
FileInputStream in = new FileInputStream(fd);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String output = "";
try {
String line;
while ((line = reader.readLine()) != null) {
output += line + "\n";
}
} catch (IOException e) {
// It seems IOException is thrown when it reaches EOF.
}
// Waits for the command to finish.
waitFor.invoke(null, pid[0]);
return output;
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage());
} catch (SecurityException e) {
throw new RuntimeException(e.getMessage());
} catch (NoSuchMethodException e) {
throw new RuntimeException(e.getMessage());
} catch (IllegalArgumentException e) {
throw new RuntimeException(e.getMessage());
} catch (IllegalAccessException e) {
throw new RuntimeException(e.getMessage());
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getMessage());
}
Link: http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App
android.os.Exec is not part of the public API, and should not be used. The fact that it hasn't been part of the product since 1.6 should be further incentive. :-)
You should use the standard Java-language facilities instead, like Runtime.exec() or ProcessBuilder.start().