Saving a singleton object - java

I know this site isn't made for questions like this but I've been searching for the answer to this I haven't found anything and I need a confirmations.
I have a singleton class which is the centre of my program, in some situations I try to save its state, however it seems it doesn't save properly, and I don't see why because It's not the first time I do this, however It is the first time I try to save a singleton, so is it possible to save a singleton object?
Here are my loading and saving codes of this object
public void Loading(String name) {
ObjectInputStream is = null;
//ignore this variable
game_loaded = 1;
try {
is = new ObjectInputStream(new FileInputStream(name + ".dat"));
//Logica is the singleton class,
//logi is the name of the variable where it is
logi = (Logica) is.readObject();
} catch (FileNotFoundException e1) {
JOptionPane.showOptionDialog(frame, "Game Invalid", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
return;
} catch (IOException e1) {
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
JOptionPane.showOptionDialog(frame, "Game Loaded Sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
}
Save:
public void saving(String nome){
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream(nome+".dat"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return;
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
try {
os.writeObject(Logica.getLogica(null));
} catch (IOException e) {
// TODO Auto-generated catch block
return;
}
JOptionPane.showOptionDialog(frame, "Game Saved sucessfully", "Load",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE,
null, new String[] { "Ok" }, "Ok");
if (os != null)
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT
Ok I may have explained corretcly, it doesn't give me any error loading, however it doesn't load the state I saved, it loads an new "Logica" as if I had created a new one

There's nothing about Singleton per se that says it can't be serialized; you can write incorrect serialization code for any class. It's not clear what's wrong, and I'm not willing to pore over your code to figure it out, but it should be possible to do.
You have an empty catch block for IOException. That's always a bad idea. You've swallowed the exception that might explain everything. Print the stack trace.

The situation you have described is not possible. Ergo you haven't described it correctly. Probably there is something wrong with your observations.
I strongly suspect an IOException or FileNotFoundException, despite your comment in another answer. You have posted code that ignores exceptions in at least four separate places. The presumption is overwhelming.
In fact your exception handling needs a lot of work. You aren't closing the file in case of exceptions for example. There are no finally blocks. You have multiple try/catch blocks where you should have one try and several catches.
Further questions along other lines of enquiry. Is the file being created? With non-zero length? Or else maybe the singleton class only has transient fields?

Related

Workaround java.io.EOFException cause by ObjectInputStream [duplicate]

This question already has answers here:
java.io.FileNotFoundException when creating FileInputStream
(2 answers)
Closed 6 years ago.
For my application I want to use a Map to act as a database. To save and load a map, I am writing/reading it to/from database.ser using this 2 methods:
private synchronized void saveDB() {
try {
fileOut = new FileOutputStream(db);
out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
fileOut.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to load into Map when application starts, so I invoke method in constructor like this:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("C:/Users/eduar/git/Multy-Threaded-Bank-System/Bank-Services/database.ser");
// also, any suggestions how can I make path to a file more flexible in case I want to run Server side of an app on different machine?
if (!db.exists()) {
try {
db.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
loadDB(); // loads database when server start
}
I am aware of what causing an error, but I don't know what should I change in my design to avoid ObjectInputStream constructor receiving empty stream!
Any suggestions on what I can do differently?
Edit: I want to note that in fresh application run database.ser is empty since there was no entries made into Map yet.
Thank You!
First why the EOFExcpetion occur?
There are no contents in file or file is empty and you tried to read file.
You can avoid the EOFException for an empty file by checking file content length if it is less than or equal to zero means file is empty. another way to check if file is empty
Some code change and it worked for me.
#SuppressWarnings("unchecked")
private void loadDB() {
try {
if (db.length() <= 0) {
// if statement evaluates to true even if file doesn't exists
saveDB(); // save to a file an empty map
// if file doesn't exist, it creates a new one
// call loadDB inside constructor
}
FileInputStream fileIn = new FileInputStream(db);
ObjectInputStream in = new ObjectInputStream(fileIn); // that is where error is produced if fileIn is empty
in.readObject();
in.close();
fileIn.close();
System.out.println(accounts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Get rid of the file.exists()/file.createNewFile() crap. All it is doing for you is masking the original FileNotFoundException problem, and turning into a thoroughly predictable EOFException because of trying to construct an ObjectInputStream around an empty stream. Handle the original problem. Don't just move it, or turn it into something else.

IF and ELSE in TRY CATCH?

I have this code
root = new Root();
root.checkRootMethod2();
TextView=(TextView)view.findViewById(R.id.textView4);
if(root.checkRootMethod2()) {
TextView.setText(Html.fromHtml("<b>TEXT 01</b><br>"));
} else {
TextView.setText(Html.fromHtml("<b>TEXT 02</b><br>"));
}
try {
if (root.RootAvailibility() && (root.checkRootMethod3())) {
try {
Process process = Runtime.getRuntime().exec("su");
OutputStream stdin = process.getOutputStream();
stdin.flush();
stdin.close();
} catch(Exception e) {
}
TextView.append(Html.fromHtml(
"<b><font color=\"green\">TEXT 03</b></font>"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
root.busybox();
TextView.append(Html.fromHtml(
"<br><b><font color=\"green\">TEXT 04</b></font>"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) {
TextView.append(Html.fromHtml(
"<br><b><font color=\"red\">TEXT05</b></font>"));
}
I wish that if if (root.RootAvailibility() && (root.checkRootMethod3())) return true Viewing a TextView that says something.If return false, another TextView that displays something else. As happens for root.checkRootMethod2 (); Same goes for root.busybox (); Do you have any idea on how I can do? Now visualize always Text04
try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
/// your code ...
}
catch(Exception e){ }
TextView.append(Html.fromHtml("<b><font color=\"green\">TEXT 03</b></font>"));
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Codes here runs always regardless of if clause.
the code (try block in your case) runs regardless of the if condition as the try block clears the scope of if block.
Either put try completely inside if block or surround both if,else statement by a single try block.
I don't know what is the need of multiple try/catch here :
try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
You can add one more catch(Exception e) to the upper try/catch block and that will serve the same purpose.
Secondly there is no else part to this if (root.RootAvailibility() && (root.checkRootMethod3())). So, if it is false the program will simply move forward.
Well you're always going to see Text04 because there's no conditional that excludes it. The try catch block it's in is at the top level.
It would help if you could provide a short, self-contained, compilable example of your code. There's clearly other potentially relevant code missing. For example, the try that goes with that last catch block. Also, it might help you to comment the beginning and end of your code blocks so that you can tell what's included in the if else statements.

Java PrintStream Questions

I am trying to revise a java code to write something into a txt file. The original code is:
try {
out = new PrintStream(system.out, true, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I use FileOutputStream to do this, and revise the code to:
try {
FileOutputStream os = new FileOutputStream("wiki.txt", true);
out = new PrintStream(os, true, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it doesn't work, the error is:
Wikipedia2Txt.java:56: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
FileOutputStream os = new FileOutputStream("wiki.txt");
^
1 error
I try two ways: 1, I make a wiki.txt file manually on disk; 2, no wiki.txt exist before run the code.
But either doesn't work. It just stopped when compiled.
So what is going on?
Thanks.
Java is not telling you that the file is not found, just that it may not be found at runtime, and your program is not ready to handle it.
Here is one way to address this:
try {
FileOutputStream os = new FileOutputStream(file, true);
out = new PrintStream(os, true, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException fnf) {
// TODO Auto-generated catch block
fnf.printStackTrace();
}
Here is another way:
try {
FileOutputStream os = new FileOutputStream(file, true);
out = new PrintStream(os, true, "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
fnf.printStackTrace();
}
The first way ensures the compiler that your code is prepared to handle both exceptions separately; the second way ensures the compiler that your code is prepared to handle a superclass of both exceptions. The two ways are not the same, because the second one covers more exceptions that the first one.
Finally, there is an alternative to silence the compiler by declaring your function with a throws block (either a common superclass or the two individual classes would do). This is a way to tell the compiler that your function has no idea of how to handle these exceptions, and that they should be handled by a caller. The consequence of this approach is that every caller of your function must put a try/catch around the call, or declare the exceptions using throws.
The signature of the FileOutputStream constructor that you're using is public FileOutputStream(File file) throws FileNotFoundException. This means it is a checked exception which you have to handle. Therefore make sure that your method in which you have written this code either handles this exception (i.e. specify this exception as part of the catch block) or you specifically throw this exception.
So either of the following would work for you:
Specify in catch block
try {
FileOutputStream os = new FileOutputStream(file, true);
out = new PrintStream(os, true, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Or make your method throw this exception - so your method signature would be something like return_type method_name (params_list) throws FileNotFoundException
You need to handle the situation when the file is not found.
Try this:
try {
File file = (..your code..)
FileOutputStream os = new FileOutputStream(file, true);
out = new PrintStream(os, true, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// Handling a situation when file is not found.
e.printStackTrace();
}
Your IDE (for instance Eclipse, IDEA, NetBeans) should provide additional help in such situations. As you have generated stubs, you are probably already using IDE. Isn't your code red-underlined?
You are just trampling upon one of the sore spots of Java: checked exceptions. There's a myriad of exceptions that may happen when your code is running, but only some of them must be declared in advance. My preferred way to handle your piece of code would be to wrap any and all checked exceptions into a RuntimeException that you can handle somewhere else up the stack trace:
try {
FileOutputStream os = new FileOutputStream(file, true);
out = new PrintStream(os, true, "UTF-8");
} catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException(e);
}
In most cases handling exceptions right at the spot where they happen is wrong and leads to swallowed exceptions and generally unreliable, hard-to-debug code.
In a well-engineered application all exceptions that represent a failure—rather than an expected alternative situation—must be propagated up the stack frame towards the so-called exception barrier, where all failures are uniformly handled.

Reflecting methods to clear Android app cache

I am trying to clear the app cache of other android apps besides my own. To do this, I am using reflection on the PackageManager class. However, whenever I initialize the method before I invoke it, it always ends up being null.
private void initiateClearUserData() {
// Invoke uninstall or clear user data based on sysPackage
String thePackageName;
PackageManager pm = speedy.this.getPackageManager();
List<ApplicationInfo> installedApps = pm.getInstalledApplications(0);
ApplicationInfo ai;// = installedApps.get(0);
ActivityManager.RunningAppProcessInfo process;
for(int x=0; x<4; x++){
ai = installedApps.get(x);
Here is where my problem is:
thePackageName = ai.packageName.toString();// mAppEntry.info.packageName;
Method deleteApplicationCacheFiles = null;
mClearCacheObserver = new ClearCacheObserver();
try {
deleteApplicationCacheFiles = pm.getClass().getMethod(
"deleteApplicationCacheFiles", String.class, PackageManager.class);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(deleteApplicationCacheFiles!= null){
try {
deleteApplicationCacheFiles.invoke(thePackageName, mClearCacheObserver);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Toast.makeText(speedy.this, "Hell naw",
Toast.LENGTH_SHORT).show();
}
}
}
Because Method deleteApplicationCacheFiles is null, my toast message shows up. Any suggestions?
Take a look at the docs for Security on Android: http://developer.android.com/guide/topics/security/security.html
A central design point of the Android security architecture is that no application, by default, has permission to perform any operations that would adversely impact other applications, the operating system, or the user. This includes reading or writing the user's private data (such as contacts or e-mails), reading or writing another application's files, performing network access, keeping the device awake, etc.
It sounds like the system will block you from doing this (through reflection too).

how can i call a throwable method inside a runnable, for creating a new thread

while trying to create a progressbar in android i came across this problem.
i am following this example : http://developer.android.com/reference/android/widget/ProgressBar.html
my problem is that one of my methods i want to call has to be inside a try and catch
how do i do that inside of a runnable?
Runnable SendThread = new Runnable()
{
try
{
GetAndConvertImagesToPdf();
mProgStatus = 30;
mProgress.setProgress(mProgStatus);
title.setText(R.string.sendingTitle);
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
};
i get this error:
"Syntax error on token try, delete this token"
how can i resolve this?
thank you
u put the try in the class body its not in any method or block
this is more like it
Runnable SendThread = new Runnable() {
public void run() {
try {
GetAndConvertImagesToPdf();
mProgStatus = 30;
mProgress.setProgress(mProgStatus);
title.setText(R.string.sendingTitle);
}
catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Sorry I am not able to answer your question but I have one advice,Try to explore about AsyncTask it will help you to run a background thread and it will let you update your UI thread as well at same time. however good luck for your current question.
link : http://developer.android.com/reference/android/os/AsyncTask.html
Happy Coding!

Categories