Intent.putExtra vs. getJSONObject - Android - android

I have a question regarding the performance of an application.
I have an object in an external database and I have already extracted all the data about it from the database, including unique id. I start a new activity, but I want to use the same info for the same object in the new activity - what will be faster - include all the strings I already obtained via getJSONObject as extras for the intent or include just the object's id as an intent extra and make a new query to the database, receive the response and obtain the json response once again?
And how could I test what method is faster than the other?

Database query is a more expensive action than just passing the strings in the intent (especially if you pass the JSON string itself, not each string inside it) so if you're going to use the same data, I think you should pass it with the intent, however, this is not something that is hard to test and measure.

Related

where does the data I passed using putExtra() method of intent to another activity get stored?

my Question is :
1 - If I send data to another activity where does it stored ?
2- what is the difference between put the parameter key of putExtra() method as builtin predefined string like EXTRA_TEXT and put a key with a random name
like "mymessage"
i.e
what is the difference between this code
public void go(View view)
{
String mytxt="hellow";
Intent i=new Intent(this , SecondActivity.class);
i.putExtra(Intent.EXTRA_TEXT , mytxt);
startActivity(i);
}
and this code
public void go(View view)
{
String mytxt="hellow";
Intent i=new Intent(this , SecondActivity);
i.putExtra("mydata" , mytxt);
startActivity(i);
}
3- how does android use the key part to of putExtra method to refer to my data
4- how does getExtra() method work from where it get the data
I think that 3 ans 4 are relevant by nature to the other above parts but I want to be clear about all my questions
thanks in advance
1 - If I send data to another activity where does it stored ?
I think there are a few different ways to answer this question, but the most straightforward is: it doesn't matter.
When you use an Intent to send data to another activity, what matters is that the other activity will receive an Intent object that is populated with the data you sent. The exact mechanism of how that happened is something you (as a developer) aren't supposed to care about.
The only exception to this that's worth mentioning is the fact that data in an Intent might (depending on exactly what you're doing) be subject to "Binder transaction size limits"; your data is serialized and transmitted at some point and, if the data is too large, this will fail.
2- what is the difference between put the parameter key of putExtra() method as builtin predefined string like EXTRA_TEXT and put a key with a random name like "mymessage"
There is no technical difference. In fact, Intent.EXTRA_TEXT is defined as a simple string itself ("android.intent.extra.TEXT").
The practical difference is that Intent.EXTRA_TEXT is a well-defined, known value that any developer can use. If I'm writing a chat program, and I want to let other apps open mine and hand off message text, I can tell users that I'll look for Intent.EXTRA_TEXT for this data, and it will be easy for everyone to use.
Within your own app, it really doesn't matter what strings you use for the key in a putExtra() call. As long as you use the same string later on to look it up, you can use anything you want. The only concern here is to make sure that you don't accidentally use the same key for two different values within the same Intent.
3- how does android use the key part to of putExtra method to refer to my data
It doesn't. All the android framework does is take a bunch of key-value pairs, serialize them (if necessary), and transmit them to another activity. That other activity, however, can then use the keys to look up the values. That's why e.g. Intent.EXTRA_TEXT is cool; it's a well-defined key that anyone can use to look data up, counting on callers on the other side to have put something in the map using that known key.
4- how does getExtra() method work from where it get the data
I guess you could say that the data comes from the app's memory.
You can think of the Intent object as being a really fancy Map<String, ?>. The same way you could write String s = (String) map.get("key"), you can write String s = intent.getStringExtra("key").
Your answers are as follow.
1. When we move from one Activity to another Activity, then data is passed using Intent and this data is sent to the system OS for safe keeping for restoration later, when we reach to another activity this data is restored from OS, There is a limit of 1 MB of this data, If It crosses then we get a crash
"TransactionTooLargeException" for nougat+ android devices.
2. Intent.EXTRA_TEXT is basically a predefined string in Intent class.
public static final String EXTRA_TEXT = "android.intent.extra.TEXT";
Google has coded internally for this key, suppose If we want to share a text with an application then we send this predefined key to send that "text" which need to be shared, thus It is a Standard Reserved key for which Google has coded internally to get and utilize that text
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, "my sharign text here");
and on the other side, If we send any our key suppose "my_key" then we handle this on the other activity.
3/4.
When you pass on data from Activity 1 using putExtra() method, then all the data sent through putExtra() is packaged into a bundle, We can fetch this whole bundle in Activity2 using getExtras() method, or we can get our separate key value using getStringExtra(), getIntExtra(), getBooleanExtra() etc.
If you send extras to an activity, the extra data is not stored in a physical device like internal/external storage, but it is stored temporarily in RAM.
Intent.EXTRA_TEXT is a constant defined in the class Intent:
public static final String EXTRA_TEXT = "android.intent.extra.TEXT";
it is used with intents like sending emails and not passing data to activities, although it is not prohibited.
(and 4) The key part of the extra data is used to refer to the actual value of the data:
intent.putExtra("key1", "A");
intent.putExtra("key2", "B");
when the activity that opens wants to retrieve the extra values sent to it by the parent activity, it will check the keys:
if(getIntent().hasExtra("key1"))
String value1 = getIntent().getStringExtra("key1", "");

putExtra sting convert to variable

Sorry for the silly question but im stucked
I want to send a large amount of data to other Activity through putExtra.
Is there any way to convert the "string" in putExtra("string", data ) to a variable given that it's stupid to write 100 different strings;
The putExtra method stores the data as a key/value pair. The string is like an index to the data it is not really a form of data in itself. When you want to retrieve your data you give the string and the system then finds the string in its indexing system and pulls out your data. Think about a book. If you want to find out about a particular subject (i.e. read some data) it would be time consuming to read the whole book to find out what you need. So instead you just check the index and you are able to go straight to the section you want and get the data you need.
Put simply the answer is NO. You must use a string and that string value must stay constant so that you can retrieve your data.
The string is simply the name that the data will be referred to as. If you want to pass 100s of strings then that's pretty easy, you just have to make data be a structure that contains your strings:
String[] data = new String[200];
... fill in the strings ...
putExtra("multipleStrings", data);

Converting multiple datas into a single string for uploading using json in android

I have to submit data from 30 pages into the server.These datas from 30 pages are to be made into a single string and that i have to upload that single string into the server using json.
Each page may contain many answers tht may be either in plain text(value we receive from edit text),from check boxes(yes or no) and so on.....please suggest me a way to add all these data into a single string and upload it using json.
Based on the comment I suspect that you believe that you need to treat these "pages" as strings that you concat. However, what I think you're overlooking is that JSON is pretty versatile in how you add objects to it.
So, let's say you have the thing that you want to ship to your server and you call it
JSONObject myEntireFile = new JSONObject();
you can now add stuff to it at any time like this...
JSONObject page1 = new JSONObject();
myEntireFile.put("page1", page1);
meanwhile you can put whatever you want IN page 1 (cause that's just another serialized container).
You can keep doing this until you're ready to send it, at which time you just call
myEntireFile.toString();
which will convert your object into one long, well formatted, JSON string, that you can then open store for later use.

Alarm broadcaster, pass object or pass id and pull object from sqlite?

I need your recommendation on something. In a nutshell, I am setting up an alarm (task reminder kind of app) in which upon expiry, the broadcaster puts a notification with the task info in the notification bar. The task information are storied in 2 objects.
Should I:
1) put the task info in an intent (serialized) in which I would pull it up upon alarm expiry from the passed in intent and display the relevent info?
2) Don't pass the two objects in the intent, just pass an ID, and upon expiry I would pull the two object from my SQL lite db to display them?
which one is more efficient, better way to do it?
Thank you so much
I'd just pass the id. That will save you a lot of trouble with serialization and deserialization.

Saving Game state Android

I'm unsure how I'm supposed to save the game state of my game that I'm developing. Should I save a instance/object containing all the game information? If yes, how? Or should I save all the relative information in a .txt file and save/load information when needed?
How do you do this and what do you think of my proposals?
You can't save an Instance / Object unless you serialize it and save it to some text/binary/database file. Your two options are kind of identical therefore.
What you need to save is all information that you need to reconstruct your game state. There are probably some information that you can derive from here.
If you have just a small fixed set of variables that define your gamestate then use SharedPreferences.
If you want to keep more than one state and / or it is more complex to save use some text (xml, json, ...)/binary/database/.. representation and store that.
I can suggest to use Parse.
https://parse.com/docs/android_guide#objects
The ParseObject
Storing data on Parse is built around the ParseObject. Each ParseObject contains key-value pairs of JSON-compatible data. This data is schemaless, which means that you don't need to specify ahead of time what keys exist on each ParseObject. You simply set whatever key-value pairs you want, and our backend will store it.
For example, let's say you're tracking high scores for a game. A single ParseObject could contain:
score: 1337, playerName: "Sean Plott", cheatMode: false
Keys must be alphanumeric strings. Values can be strings, numbers, booleans, or even arrays and objects - anything that can be JSON-encoded.
Each ParseObject has a class name that you can use to distinguish different sorts of data. For example, we could call the high score object a GameScore. We recommend that you NameYourClassesLikeThis and nameYourKeysLikeThis, just to keep your code looking pretty.
Saving Objects
Let's say you want to save the GameScore described above to the server. The interface is similar to a Map, plus the save method:
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
try {
gameScore.save();
} catch (ParseException e) {
// e.getMessage() will have information on the error.
}
After this code runs, you will probably be wondering if anything really happened. To make sure the data was saved, you can look at the Data Browser in your app on Parse. You should see something like this:
objectId: "xWMyZ4YEGZ", score: 1337, playerName: "Sean Plott", cheatMode: false,
createdAt:"2011-06-10T18:33:42Z", updatedAt:"2011-06-10T18:33:42Z"
There are two things to note here. You didn't have to configure or set up a new Class called GameScore before running this code. Your Parse app lazily creates this Class for you when it first encounters it.
There are also a few fields you don't need to specify that are provided as a convenience. objectId is a unique identifier for each saved object. createdAt and updatedAt represent the time that each object was created and last modified on the server. Each of these fields is filled in by the server, so they don't exist on a ParseObject until a save operation has completed.
Retrieving Objects
Saving data to the cloud is fun, but it's even more fun to get that data out again. If you have the objectId, you can retrieve the whole ParseObject using a ParseQuery:
ParseQuery query = new ParseQuery("GameScore");
ParseObject gameScore;
try {
gameScore = query.get("xWMyZ4YEGZ");
} catch (ParseException e) {
// e.getMessage() will have information on the error.
}
To get the values out of the ParseObject, there's a getX method for each data type:
int score = gameScore.getInt("score");
String playerName = gameScore.getString("playerName");
boolean cheatMode = gameScore.getBoolean("cheatMode");
If you don't know what type of data you're getting out, you can call get(key), but then you probably have to cast it right away anyways. In most situations you should use the typed accessors like getString.
The three special values have their own accessors:
String objectId = gameScore.getObjectId();
Date updatedAt = gameScore.getUpdatedAt();
Date createdAt = gameScore.getCreatedAt();
If you need to refresh an object you already have with the latest data that is on the server, you can call the refresh method like so:
myObject.refresh();
You could use an SQLite database to save the important variables in your game. If the game is started from one class you could provide that class with two constructors, one which instantiates a normal game from the beginning and another which accepts all of the variables from your game and creates the game object from the save point.
This will allow you to have more than one game save (by saving the id along with any data) and game saves will not be lost if you ever update your game (Assuming you don't alter the database).
Do a quick search for "constructor overloading" to find out more.
If your game is not data intensive and if serializing and saving to Shared Preferences is enough, you can check out the GNStateManager component of the library I wrote to make it easy to store and retrieve the required fields of the activity marked my #GNState annotation. It is dead simple to use. Other singleton class object states can be saved too. See here for Setup and Usage information: https://github.com/noxiouswinter/gnlib_android/wiki/gnstatemanager

Categories

Resources