How to save an array of simple objects in my android app? - java

I'm currently creating my first android app and I've a simple class 'Player' I want to save a few instances (a dozen or two) of that consist of 5 ints. All I wish to use them for is for the user to be able to save and load players.
I'm currently a bit bewildered as to how to do this as googling and searching this site returns Parcelable, Serializable, JSON, Externalizable, SQL, Simple XML, shared preferences and many more techniques all of which have pros and cons and look quite complex to work given they may be slow or might not work or not be suited to the simplicity of what I wish to do.
What approach of compression and storage should I be taking?
Thanks

If you want easier solution then go with JSON or SharedPreferences. Easier to parse and easier to store.
Here is an example code I've uploaded for you. ObjectSavingTest

I think you can create a SQLite database with 12 rows and 5 columns.. for 5 integers in your class.. and rows for your player names..

Related

Android - best storage method to store objects (database or json/internal storage)

I'm new to Android development. I want to do a small app that need to store quotes from famous people. I'm going to use an Object quote to store each quote. The object will be simple and only use Strings.
I want the user to be able to add quotes, but I want them to be stored so they can be saved the next time the user open the app.
I've seen a lot of questions about how to store data and they usually give you lists of available technology. I'm wondering what are the common practices among experienced developers, what are the common use for each technology.
I know it's possible to use a database. But since I only want to store a list of quotes object I'm wondering if that wouldn't be too much.
I could store it in a file in the internal storage. But then how do I store it? Should a store it in json format and every time the user start the app I simply use the json to recreate the list of quotes.
I'm not sure which way would more practical or even if using json would be effective.
Thank you for you help!
I won't recommend you to use Shared Preferences since those are intended for very short data, say 100 kb to 1 MB. In you case you can store quotes either in an sqlite database or in a file. (One that suits your need). You can test between how much time does it take to write your quote to a file and to a database, both are good choices. In both cases you should create a wrapper class and use it according to your needs, which will make the working convenient.

How do I store objects if I want to search them by multiple attributes later?

I want to code a simple project in java in order to keep track of my watched/owned tv shows, movies, books, etc.
Searching and retrieving the metadata from an API (themovieDB, Google Books) is already working.
How would I store some of this metadata together with user-input (like progress or rating)?
I'm planning on displaying the data in a table like form (example). Users should also be able to search the local data with multiple attributes. Is there any easy way to do this? I already thought about a database since it seemed that was the easiest solution.
Any suggestions?
Thanks in advance!
You can use lightweight database as H2, HSQLDB or SqlLite. These databases can be embedded in the Java app itself and does not require extra server.
If your data is less, you can also save it in XML or Json by using any XMLParser or JsonParser (e.g. Gson()).
Your DB table will have various attributes which are fetched from API as well as user inputs. You can write query on the top of these DBs to fetch and show the various results.
Either write everything to files, or store everything on a database. It depends on what you want though.
If you choose to write everything to files, you'll have to implement both the writing and the reading to suit your needs. You'll also have to deal with read/write bugs and performance issues yourself.
If you choose a database, you'll just have to implement the high level read and write methods, i.e., the methods that format the data and store it on the appropriate tables. The actual reading and writing is already implemented and optimized for performance.
Overall, databases are usually the smart choice. Although, be careful of which one you choose. Some types might be better for reading, while others are better for writting. You should carefully evaluate what's best, given your problem's domain.
There are many ways to accomplish this but as another user posted, a database is the clear choice.
However, if you're looking to make a program to learn with or something simple for personal use, you could also use a multi dimensional array of strings to hold the name of the program, as well as any other metadata fields and treat the array like a table in excel. This is not the best way to do it, but you can get away with it with very simple code. To search you would only need to loop through the array elements and check that the name of the program (i.e. movieArray[x][0] matches the search string. Once located you can perform actions or edit the other array indexes pertaining to that movie.
For a little more versatility, you would create a class to hold the movie information with fields to hold any metadata. The advantage here is that the metadata fields can be different types rather than having to conform to the array type, and their packaged together in the instance of the class. If you're getting the info from an API then you can update or create the classes from the API response. These objects can be stored in an ArrayList and searched with a loop that checks for a certain value i.e.
for (Movie M : movieArrayList){
if(m.getTitle().equals("Arrival")){
return m;
}
}
Alternatively of course for large scale, a database would be the best answer but it all depends what this is really for and what it's needs will be in the real world.

Java/Android - Most efficient way to store many variables

I'm creating an app and I need to store hundreds of strings that can be called or used in if/else functions. I was thinking about using SQLite to try and hold a load of them but I'm not very experience with it and I'm not too sure how I can manually store strings in it. Is there a simpler way to store many different strings besides using a large array or a database?
You need to ask yourself how you're going to use these strings. Will you load them all once into memory when the app starts up or will you constantly be pulling bits and pieces throughout the application's life-cycle? If your answer is the latter than a viable option in Android would be to use SharedPreferences which uses a key/value pair format to store data on the device. If your answer is the former then a database (SQLite) would probably be better.
See Google's documentation for more information on SharedPreferences.

Organizing many texts by swapping instances

I am planning to develop an adventure-like game.
For that I am going to have a lot of instances of classes with different texts (basicly strings).
I dont want to hardcode this many texts, so i am looking for a way to do it better.
The guy in this video ( https://www.youtube.com/watch?v=8CDePunJlck ) is using json to write text files for each class instance manually and parse them automatically into instances. That goes into the right direction.
I´m looking for more information on that, so how is this procedure called?
Its said in the video that this also works with databases?
Is there a way to design a little bit more complex stuff with things like this?
E.g. I have the case that I would like to output different texts if e.g. a local or global variable is over a treshold etc. Can I do this without hardcoding and write an own class for each of my proposed instances?
Thank you!
Your question is quite broad, and it is hard to give a definitive answer. Here are some thoughts - hope you find it helpful.
You are right that you don't want to hardcode strings. The alternative to this is storing strings as external resources, and loading them into your game at start. There are numerous ways the resource can be organized; the choice depends on your programming platform, game architecture etc. For example, you can use simple name-value approach:
AREA_1_DESCRIPTION: You stand next o a small white house.
ITEM_22_DESTRUCTION: The nasty snake disappears with a loud "Bang!"
Using JSON or XML will give you more structured storage, which can be of great help, since you can organize your texts so that it is easier to use them in the code:
<item id="375" name="Great Sword">
<short_description>A Great Sword of Darkness</short_description>
<long_description>The sword has almost black blade with some unknown runes engraved</long_description>
</item>
If your programming system can access a database, then you can do something similar and store texts in the tables; this, however, might make it more difficult to edit texts later. If you want to go this way, I would still recommend using XML or JSON to store the texts, and making the game import texts in DB on the first run.
You probably will also need some sort of simple template-handling engine to be able to re-use some strings. You can start with creating your version of Java String.format() method. Your method might take as a first argument an ID of a string in your string catalog, and use some simple placeholders for the parameters. Suppose you have the following entry in your catalog:
FIRE_GEM_ACTION: "The Fire Gem touches %% and in %% seconds it turns into ashes."
Then you can write a method that will do something like this:
int delaySeconds = 5;
String message = MyTemplateProcessor.process(FIRE_GEM_ACTION, "old map", delaySeconds);
The function will take the string from the catalog, search for the occurrences of the placeholders (%%) and replace them sequentially with the parameters, so in the message you will get: The Fire Gem touches old map and in 5 seconds it turns into ashes.
In general, I would recommend you to have a look at some systems specially designed for creation of adventure games. Inform 7 will be a good starting place: http://inform7.com/learn/

Saving object for future use

I am writing a program (a bot) to play a Risk-like game in an AI competition. I'm new to programming so I've used some very basic coding so far. In this game, each round the program receive some information from the game engine. In the program, I have a class BotState, which allows me to treat information from the current round, such as the opponent bot moves, or the regions currently under my control, etc. This information is put in some ArrayLists. I have some getters to access this information and use them in the main class.
My problem is that each round, the information is overwritten (each round means a new run of the program), so I can only access the information from the current round. What I would like to do is save all of the information each round, so that for example if the game state is at round 10, I still can access the moves that the opponent made on round 8.
I looked for ways to solve this problem, and I came across something named "object serialization". I didn't quite understood how it works, so I would like to know if there is a simpler/better way to do what I want, or if serialization is the way to go. Thanks for your help.
edit: I can't link the program to my disk or a database. I upload the source files of the bot to the game server, so everything has to be in the source files
Object serialization should be fairly simple for your case.
Simply put it is a way to store your object on disk and
to later on take data from the disk and recreate your object
in memory in the same state it was before serializing it.
Another way is to define some sort of representation yourself
e.g. as an XML chunk and for each object and to store those
chunks in an XML file. You can view this as a custom serialization
but it's still a serialization.
Another way is to store your objects into a database.
All in all, you need some permanent/persistent storage
for your objects (whether it's the disk directly or a DB
/which is again using the disk at the lowest level/).
Consider using a modeling framework for your application. The Eclipse Modeling Framework (EMF) comes with a simple XMI serialization built into it. If your model is small and/or simple enough it may be worth it. Have a look at this EMF introduction tutorial and this tutorial on serialization in EMF.
Also, have a look at this question: What's the easiest way to persist java objects?.

Categories