Add a field to existing vector - java

I have a standard program with a list of interview questions that people use when interviewing new members. The questions are hard coded, the interviewer records the answer to the questions. The answers when submitted are added to an object (called iQuestions) and then stored in a .txt file on the server. Well times change and now we want to add additional questions to the list, which is easy enough to do, however when I change the iQuestions in both the server and client, the old records bomb out with a "serialized object" error (the object saved is not the same as the object in the program that I am trying to get from. What is the easiest way to get past this?

This is where not having the static serialVersionUID defined in a Serializable class can burn you later. As you state, your new version of the serializable class is different than the one that was used to save off data and as such the "automatic" deserialization cannot determine how to read the data back in to your new version of the class ( http://www.javapractices.com/topic/TopicAction.do?Id=45 ). If you still have access to the original iQuestions class, you might consider writing a converter that deserializes the questions using the original class and then write out the relevant data into another format (perhaps using a database to store the questions would be more reliable and easier to update or storing as JSON in a text file for simplicity?).

Related

Android: Performance when calling Json file data multiple times from different classes

I'm working for my first time with Json files as data for my app, and I have been thinking about how is the best option to save a json file to make it accessible from different classes.
It is easy, I have a JSON file with different rated for currency conversions. I need to convert the data that I show in different currencies in different modules of my app continually.
So I just want to know a good way to store my json data and not load my Json file every time that I need to check a currency rate and find a way to do it more simple, maybe as a hashmap in my BaseActivity which is extended by the rest of my activities and just call it, or a static class with all the methods related with currency rates. I also thought about save it in a sharedPreferences.
It just a question for check the opinion of more people about the best way looking for app performance to continually call data from Json files.
I am not a financial expert but as far as I know currency conversion rates are applied on a daily basis. Also I have not worked on Android but the answer below is more problem-specific rather than technology specific and hence I assume that you would be able to map this to Android primitives.
I would hence design my strategy for maintaining the currency conversion rates as below:
Fetch the currency conversion rates the first time the app starts. Process this data and store it in memory within a HashMap for the lifetime of the app. Also, place this data into a more permanent store (e.g. SharedPreferences).
Refresh this data periodically using a service that runs once every
24 hours fetch the updated data. Process the fetched data in a
manner similar to above.
Notify the app that the currency rates have been refreshed. In case
the app is running it can referesh it's memory caches.
As about the class design - the hash map storing the currency exchange rates should be stored in a separate class say CurrencyConversionRateCache. This class exposes all method required for your activity classes to fetch conversion rates. The class also gets notified from the background service (possibly using Intents in Android) when new currency conversion rates have been downloaded. This way the cache itself is responsible for ensuring the validity of it's data keeping activity classes simple.
Hope this gives you some headstart towards solving your problem.

Android Intents and Lists

I plan on reading several files when my app/game is created and using the information from them for the entirety of the app. I also have to write to the file at one point.
I have two files. One is a 2-column text file that I'll turn into a dictionary for fast searching. The other is a text file that has 11 columns. I'll make a dictionary out of two of the columns, and the other data I need kept as is so I can write to the columns to count the amount of times something happens in different circumstances for datamining.
Currently, I've turned the second file into a list of a list of strings, or List>. I can't figure out how to pass that around in intents. ".putStringArrayListExtra" only works for a list of strings.
Am I going about this the wrong way entirely? This is my first real Android app.
In order to store a data structure into an Intent, it has to be either serializable or parcelable. If your data structure is neither of them, you might create a class that would implement Serializable and manage it. A good example might be found here.
Once done, you then might use Intent.putSerializable(...) to store your data structure. See this:
Using putSerializable in Android
Additionally to this, if you could convert your structure into a JSON structure, you'd already have it done since it would be treated as a String. If not, the above solution should be easy to do.

writing data in to files with java

I am writing a server in java that allows clients to play a game similar to 20 questions. The game itself is basically a binary tree with nodes that are questions about an object and leaves that are guesses at the object's identity. When the game guesses wrong it needs to be able to get the right answer from the player and add it to the tree. This data is then saved to a random access file.
The question is: How do you go about representing a tree within a file so that the data can be reaccessed as a tree at a later time.
If you know where I can find information on keeping data structures like trees organized as such when writing/reading to files then please link it. Thanks a lot.
Thanks for the quick answers everyone. This is a school project so it has some odd requirements like using random access files and telnet.
This data is then saved to a random access file.
That's the hard way to solve your problem (the "random access" bit, I mean).
The problem you are really trying to solve is how to persist a "complicated" data structure. In fact, there are a number of ways that this can be done. Here are some of them ...
Use Java persistence. This is simple to implement; make sure that your data structure is serializable, and then its just a few lines of code to serialize and few more lines to deserialize. The downsides are:
Serialized objects can be fragile in the face of code changes.
Serialization is not incremental. You write/read the whole graph each time.
If you have multiple separate serialized graphs, you need some scheme to name and manage them.
Use XML. This is more work to implement than Java persistence, but it has the advantage of being less fragile. And if something does go wrong, there's a chance you can fix it with XSLT or a text editor. (There are XML "binding" libraries that eliminate a lot of the glue coding.)
Use an SQL database. This addresses all of the downsides of Java persistence, but involves more coding ... and using a different computational model to access the persistent data (query versus graph navigation).
Use a database and an Object Relational Mapping technology; e.g. a JPA or JDO implementation. (Hibernate is a popular choice). These bridge between the database and in-memory views of data in a more or less transparent fashion, and avoids a lot of the glue code that you need to write in the SQL database and XML cases.
I think you're looking for serialization. Try this:
http://java.sun.com/developer/technicalArticles/Programming/serialization/
As mentioned, serialization is what you are looking for. It allows you to write an object to a file, and read it back later with minimal effort. The file will automatically be read back in as your object type. This makes things much easier than trying to store the object yourself using XML.
Java serialization has some pitfalls (like when you update your class). I would serialize in a text format. Json is my first choice here but xml and yaml would work as well.
This way you would have a file that doesn't rely on the binary version of your class.
There are several java libraries: http://www.json.org
Some examples:
http://code.google.com/p/json-simple/wiki/DecodingExamples
http://code.google.com/p/json-simple/wiki/EncodingExamples
And to save and read from the file you can use the Commons Io:
import org.apache.commons.io.FileUtis;
import java.io.File;
...
File dataFile = new File("yourfile.json");
String data = FileUtils.readFileToString(dataFile);
FileUtils.writeStringToFile(dataFile, content);

How to forget serialized data after read in Java?

I'm making a program that opens a previous saved file through serialization and want to create a new one, however, data stays in.
How can I make the program forget the data?
If you specify an attribute with the keyword transient, then it will not be serialized. If you're saving the data by serializing objects and writing them to files, this may be what you're looking for. Here's an example of using the transient keyword.
Shouldn't creating a new instance of whichever class you are serializing give you such an 'empty data record'?
Using the example of a text editor you use, you would have, say, a Document class which completely encapsulates a text document and assume you use serialization to save it, then simply new Document() would give you an empty document... Until you fill in some text (or data in your program) you shouldnt open a file...
Assuming you meant a tree of Employee data, or a tree data structure with Employee objects at its nodes, then creating a new such tree will give you what you want.
Think, how did you create the first data set that you serialized? Just repeat that process...

How to get address of a Java Object? [duplicate]

This question already has answers here:
Is there a way to get a reference address? [duplicate]
(5 answers)
Closed 8 years ago.
Is there a way to get address of a Java object?
Where the question comes from?:
At First, I read properties file and all the data from file was placed into table. Properties file can update. So, I want to listen that file. I listen an object using PropertyChangeSupport and PropertyChangeListener.
updatedStatus = new basit.data.MyString();
updatedStatus.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
//After changes "i", we inform the table model about new value
public void propertyChange(PropertyChangeEvent evt) {
Object objec=evt.getNewValue();
tableModel.setValueAt(objec.toString(), 0, 5);
}
});
If updatedStatus changes then i update table. MyString class have private String "Value". I want to listen properties file. So, it should make updatedStatus.value and String of Properties File equal at the same address. If i can do it, so i don't need to listen properties file.
updatedStatus.setValue(resourceMap.getString("HDI.Device.1.Name"));
I tried to use StringBuffer, but i couldn't achieve it. That's why, I asked the question.
Firstly - no, you can't get the address of an object in Java; at least, not pure Java with no debugging agent etc. The address can move over time, for one thing. You don't need it.
Secondly, it's slightly hard to follow your explanation but you certainly won't be able to get away without listening for changes to the file itself. Once you've loaded the file into a Properties object, any later changes to the file on disk won't be visible in that object unless you specifically reload it.
Basically you should listen for changes to the file (or poll it) and reload the file (either into a new Properties or overwriting the existing one) at that point. Quite whether you also need to listen for updates on the string container will depend on your application.
System.identityHashCode(obj) delivers the next-best thing: a number unique for each object. It corresponds to the default Object.hashCode() implementation.
To quote the API: "As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)".
we can get address of an object in memory. Well how? it is like that;
using sun.misc.Unsafe class in java.
create new Unsafe object and use the getAddress(Object); method and it will return a long value that is address.
and also there are many methods for this class.
you can change the values in this address using putInt(Object,long offset, int value) or like this method.(getting some value getnt(Object)).
Note: this class is really UNSAFE . if you make wrong things on your project, JVM will be stopped.
Look into Apache Commons Configuration. This library has support for dynamic reloading of (for example) property files. See here.
The best way to observe if some file changes is IMHO to make a hash value with sha1 or mda5 and save the value in a cache. And you make a Thread that every minutes, seconds, depends how often you watch file changes, and make hash value over the file. So you can compare this two values and if the values are not equivalent so you can reload the new file.
Java not like C/C++. in C++, you will often work with address (that C++ programmer has a concept call pointer). But, I afraid that not in Java. Java is very safe that prevent you to touch its address.
But, there other ways maybe same with your idea is use HashCode. HashCode of an object base on their address on HEAP.

Categories

Resources