Intent::putExtra() and EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; - android

My code is as follows:
First, I was wondering about line 20:
I had two questions:
a. Why is MY_MESSAGE assigned to com.example.myfirstapp.MESSAGE?
b. What is com.example.myfirstapp.MESSAGE?
c. I mever made MESSAGE anywhere; is this automatically made like the variables in r.java file, or do i need to make it somewhere?
Secondly, about line 40: intent.putExtra(EXTRA_MESSAGE, message);
I am not sure if this method adds a message to the upcoming activity to be called or what... Partly, I am struggling to understand this due to not knowing the point of an Intent fully.
I want to read my 200 fundamental section on what everything is, but I have set deadlines and I have been told not to take that approach for the time being for this project
With given the explanation of the Android Docs , I know an intent is:
The Intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed
A.) Could someone explain what the intent is used for or give some better quick articles than just the docs?
B.) Explain what putExtra( ) does and and these parameters more clearly:
name The name of the extra data, with package prefix.
value The String array data value

An Intent is appropriately named; it's what you want to be done. As the documentation says:
Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
By your code, you are familiar with starting an Activity via Intent:
new Intent(this, DisplayMessageActivity.class);
This uses your current Activity as the context from which to start the Intent, and gives the target class to launch. You already know this, I think. Basically, the Intent is just a guide for the Android device to follow so that it launches the right target with the right information.
Onto your real questions:
"What is the intent used for?" This is described above; basically, it's used to tell the OS what your target is, where it's coming from, and what data it should provide. You've seen most of this in action without realizing; this constructor is the one you've been using, detailing the "from" and "to" portions. When you use putExtra, you are providing the Intent with data it can give to the "to" part of the code.
The name parameter is best summed up by the documentation: "The name of the extra data, with package prefix." This is like a key in a HashMap; it is a string identifier of the content you are packaging. They tell you to use your package's prefix, just to prevent confusion. In your case, you should be using "com.SG.Three_Piece_Radio.YOURKEYNAME"; this does not have to be declared anywhere, nor is it a constant. Just a string. The value is just the contents of the extra (the data); this can be a ton of different things--short, int, String, Parcelable, and many more. (These can all be found in the various putExtras in the Intent docs.)
Once your Intent is received, you can use those same bits of data (for example, String myStr = getIntent().getStringExtra("com.SG.Three_Piece_Radio.YOURKEYNAME");) and do whatever you wish with them in the Activity you called.

I think people have been very helpful here in giving great explanations about Intent itself and its purpose. I got to learn a lot from these answers.
However, there was a small aspect that I think needs a little more explanation.
So to answer your very first question that says :-
a. Why is MY_MESSAGE assigned to com.example.myfirstapp.MESSAGE? b. What is com.example.myfirstapp.MESSAGE? c. I mever made MESSAGE anywhere; is this automatically made like the variables in r.java file, or do i need to make it somewhere?
My answer would be :-
So as all explained, putExtra is meant for carrying additional information/data along with the intent for the new activity that is going to be started. This additional information that putExtra carries is given in Intent in the form of a Key-Value pair.
In this Key-Value pair, the Key syntactically always has to be a String.
In your case, the value is also a String and the "key" can be any random string.
Now, to make sure that the system does not confuse your KEY with some other app's KEY you should always append the entire packet structure of the string along with it. And hence you use :-
com.example.myfirstapp.MESSAGE
where MESSAGE is actually the name of the key, (the String as is required, as I mentioned above) that would be associated with the string value that would be passed with the intent to the new activity.
Now you could have very well written the following as well :-
intent.putExtra("com.example.myfirstapp.MESSAGE", message);
instead of :-
intent.putExtra(EXTRA_MESSAGE, message);
but then this would reduce the flexibility of your code for changes to be made later. As for any changes in the key name you will have to change it everywhere. So to avoid this we rather assign the name of our key (in your case, MESSAGE) to a String variable (in your case EXTRA_MESSAGE).
This also makes it easier for other activities to reference this key by a simple String variable. And so to make it accessible to other activities (coupled with other self explained features)you make it as :-
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
Please correct me if I happened to miss something or went wrong somewhere.

The most common use of intents is to start new activities (screens)within an application (line 41). The extras Bundle is a way of passing data between activities. Extras are entered as key value pairs so EXTRA_MESSAGE is a key is used to identify a particular value so it can be retrieved and used by another activity.

Related

does the context passed on getDefaultSharedPreferences affects the result?

I'm getting an weird error so I'm trying to eliminate the possibilities.
Does the context passed to PreferenceManager.getDefaultSharedPreferences() changes the result?
I mean, when i'm writting setting to my app i never pay attention which context i pass to this method since it is a valid context...
Sometimes i put the Activity, sometimes the Appliaction whatever context i've on hands
Is it wrong? I've noticed that i'm getting wrong preferences values at some point, and i dont know if there is a bug in my code or if this be
It doesn't matter whether you provide an Application or an Activity as the Context parameter for PreferenceManager.getDefaultSharedPreferences().
If you look at the source for getDefaultSharedPreferences():
return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
getDefaultSharedPreferencesMode());
Looking further, into getDefaultSharedPreferencesName(context):
return context.getPackageName() + "_preferences";
This means that for any Context of your application, you'll get the same SharedPreferences back, as your application ID does not change based on Activity or Application.
The only time you could run into a potential issue is if you are manually creating a Context for another package (e.g. using Context.createPackageContext()).
SharedPreferences data stores all have a name, and as long as you use the same name you'll always get the same data store.
Hat tip to #kcoppock who has pointed out that in the particular case of PreferenceManager.getDefaultSharedPreferences(), the only thing the generated name is dependent on is the Context's package. Since any Application or Activity instance you pass is exceedingly likely to have the same package name, in your case you should always get the same data store.
There are other ways to retrieve SharedPreferences stores, though. Activity.getPreferences() will generate the name based on the Activity's class name, so calling getPreferences() from inside two different activities will give you two different data stores.
You can also call Context.getSharedPreferences() directly (both PreferenceManager and Activity just call through to this) and pass a data store name explicitly. There's no requirement for how the name should look; as long as you use the same name you'll always get the same data store.
https://developer.android.com/reference/android/content/Context#getSharedPreferences(java.lang.String,%20int)

When creating and loading a "savedInstanceState", why is it necessary to use constants for the keys?

Looking through this tutorial: http://www.newthinktank.com/2013/04/android-user-interface/
The app assigns a string constant for each value to be saved. Then when the savedinstancestate is made, the values are assigned to the keys. And when the savedinstancestate is loaded, they are found using the keys. Why is it necessary to use the constants as the keys? What's wrong with just using s a string as the key like this?
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putDouble("TOTAL_BILL", finalBill);
outState.putDouble("CURRENT_TIP", tipAmount);
outState.putDouble("BILL_WITHOUT_TIP", billBeforeTip);
}
You dont have to use constants if you dont want to, its just a convenience method to not make coding mistakes. Actually with time you will find that you are using a lot of bundles, sharedpreferences and other components requiring use of some string keys. In case of savedinstance handling in activities they are used in single class, but sharedpreferences or using bundles with startActivityForResult thats not the case, such string key constant is used by different classes, sometimes in different packages. Its good practice to manage such constants in some ordered manner. For shared preferences I use separate class called Consts, for startActivityForResult bundle arguments I try to keep keys in Activity beeing called (because it can be called by different activities).
also it makes it easier to prefix such constants with some well know word, ie.: KEY_ , in provided tutorial I would use rather names as KEY_TOTAL_BILL, KEY_CURRENT_TIP, ... This makes it easier to find them using code completion, especially when you have lots of other such fields in class.
If you mistype the key, it could be difficult to find where the error lies. It is much safer to use a constant.
Same goes for storing and retrieving data inside an Intent, you wouldn't want to go through every activity that handles that Intent looking for a mistyped key.

Share a value across all views of my activity

This question is more like a discussion about how you guys would do it.
I'm developing an application that has an Avatar Creation, but this creating occurs across two different Activities.
In the first one the user selects whether is man or a woman and a name, in the next Activity the user has to select his face, hair, clothes and etc.
Since the views for hair and etc changes if the user is a man or a woman how would you implement a way to pass the gender value to all the Views?
I was thinking about using a static member to hold the value so I could access inside my views, or maybe I should use SharedPreferences to do it.
I think using the SharedPreferences is a more elegant way to do it but I'm wondering if there isn't any other better and more elegant way of doing it.
Has anyone thought about other implementations?
If its only a small information like "gender" i don't see much harm using "Static" variable(Ofcourse the static variable will become null if your app crashes when its in the background).
SharedPreference will come good if you want the information to be persistent(But i don't see you need this).
One more choice is you do can extend the application class to store the static data across activities.
You could pass the gender to the next Activity with start activity Intent. Example:
Intent intent = new Intent(this, NEXT_ACTIVITY.class)
intent.putExtra("gender", genderVariable)
startActivity(intent);
And retrieve the value in NEXT_ACTIVITY class on onCreate() like this:
String genderVariable = ""
Bundle parms = getIntent().getExtras()
if (parms != null) genderVariable = parms.getString("gender")
Then, pass gender to all your views and persist the genderVariable on SharedPreferences or onSavedInstanceState bundle. I prefer onSavedInstanceState.
Hope it helps.
I think there are many ways of which 4 I think are better. It ofcourse depends on what kind of data you want to store.
For Lists or hashmaps, using a singleton class would be helpful.
Using a static class would help, but might leak memory. You should be very careful and always check using logcat, MAT before releasing your app.
Using preferences or database.
Passing data as Intent extra (parcelable if needed).
Using SharedPreferences would be the better way to share some global values across the application.

Problems accessing my strings.xml items… i got numbers and not the string value

i found this problem some time ago, but i solve it using this: getString(), or this: getResources().getString()
but now, for this case, it doesn't works, i think it's because i need to get the string values on a NON ANDROID ACTIVITY CLASS. I need the resource values on a remote connection class, that doesn't extends any kind of activity or service.
how i can acces to the variables from my strings.xml on this normal class?
this is the code where i get the error (it gets an integer, and not the string value)
String a =R.string.totalpermission;
Take a look at these two answers (are the same XD):
How to obtain AssetManager without reference to Context?
How can I get a resource content from a static context?
Just an advice: try to read some basic concepts... it seems you don't understand what the R class is and how to use it. Trust me, you waste less time studying than trying to figure out how things work.
I'll add something to existing answers since I found it very useful.
To get your strings you have to use a Context. Your activity will work just great.
String string = getString(R.string.myString);
But if you have something more complex... for exemple
R.string.result -> "You %1$s %2$d cats"
String result = getString(R.string.result, killed ? "killed": "saved", count);
That would give you a result like that:
You saved 10 cats or You killed 2 cats... and so on. You can pass parameters and positional arguments in strings will get replaced by your arguments in getString.
All Android resources are referenced via a resource ID, like R.string.totalpermission. You can see those numbers in R.java (although there's no reason to ever do that).
In cases of strings, you can easily get those using Context.getString. Bonus: You can even pass optional arguments and add dynamic strings that way. You always have a context - how are you getting called? If you really don't have a context, you can create one for the package your resources are in.

what is an immutable reference?

hi i have found Uri as immutable reference i dont know what it is the exact meaning of immutable reference... can anyone help me?
It's a variable that cannot be changed once set. Very useful when you have multithreaded code since being able to change a variable's value might be a source of many hard to find problems in your code.
If it's immutable, it's usually good.
A good example of an immutable class within the .NET Framework is System.String. Once you create a String object, you can’t ever change it. There’s no way around it; that’s the way the class is designed. You can create copies, and those copies can be modified forms of the original, but you simply cannot change the original instance for as long as it lives, without resorting to unsafe code. If you understand that, you’re probably starting to get the gist of where I’m going here: For a referencebased object to be passed into a method, such that the client can be guaranteed that it won’t change during the method call, it must itself be immutable.
In a world such as the CLR where objects are held by reference by default, this notion of immutability becomes very important. Let’s suppose that System.String was mutable, and let’s suppose you could write a method such as the following fictitious method:
public void PrintString( string theString )
{
// Assuming following line does not create a new
// instance of String but modifies theString
theString += ": there, I printed it!";
Console.WriteLine( theString );
}
Imagine the callers’ dismay when they get further along in the code that called this method and now their string has this extra stuff appended onto the end of it. That’s what could happen if System. String were mutable. You can see that String’s immutability exists for a reason, and maybe you should consider adding the same capability to your design.
EX: string is immutable...
if u have for ex string s =" whatever" and u output it with uppercase letter..for ex
Console.Write(s.ToUpper())the console will print u WHATEVER...but the string s will still be whatever... unlike the mutable type which will change the string from whatever to WHATEVER
"immutable" means "can't change the value"
"mutable" == "changeable"
"immutable" == "not changeable"
In java , every thing is treated as String and object , Now try to think that if have created a program of 10000 lines and in this there you have added "public" 100 times so do you think that every time this public is created in storage . else what we can do , we can created something like that when ever we find something like this we will fetch it from there there ( String pool )

Categories

Resources