Android: getIntent() is deprecated - android

My program consists of a MainActivity and two fragment activities. I need one fragment to take a String value from the user and pass it to the second fragment.
I am trying to wrap my head around how to do this. Since I am familiar with intents, I found this answer on another post and decided to try it out. Everything looks fine until I get to step 4, when I try to use Intent i = getIntent(); in my second fragment, Studio won't let me use it and says "getIntent(java.lang.String) is deprecated".
This doesn't make sense to me since I have used getIntent() in other programs without issue, and it is letting me use it in my MainActivity (step 2 from the other post) without screaming at me.
I know this can be done without using intents, but I can't figure it out and can't find any really thorough tutorials in order to do so. So I guess my questions are:
Can I make intents work for this purpose still? What should I do to get around this deprecation issue?
Any other advice, explanations, or links to "explain it like I'm 5" tutorials would be very helpful and welcome. I have Googled and read a few, but I am still not understanding this and am becoming increasingly frustrated. It seems like this should be a relatively simple concept.

It is too late for answer but still I am providing my answer for other persons. It is happen because Intent is basically work with an activity. And fragments are not activity, but attached to activity. So simply you need to do this:
Intent intent=getActivity().getIntent();

Having the same problem while passing Object from an Activity to a Java Class.
Here is what I did
This Activity sends data
Salary newSalary = new Salary();
Intent intent = new Intent(ViewData.this,Data.class);
intent.putExtra("SalaryObj", newSalary);
It recieves data(In Data.class)
Here I tried this but Android Studio says getIntent is deprecatedIntent intent = Intent.getIntent();
So What can I use in place of getIntent(), because all the solutions I find on Internet to this problem, uses getIntent().
EDIT:
I was playing around with this and found that I was trying to receive data in Java Class(Not an Activity). But when I used it in an Activity then it works fine. But it takes me to another question that how to send data from an Activity to Java Class(which is not an Activity).

On your onCreate
val bundle = intent.extras
if (bundle != null) {
idEmployee = bundle?.getString("idEmployee", "")
idClient = bundle?.getString("idClient", "")
listAvailable = bundle?.getStringArrayList("listAvailable") as ArrayList<String>
Log.i("list:", "$listAvailable" )
}

It means, that this method could not be supported in further releases. The method is still in the API for backward compability for an unspecified amount of time. Mostly it is dangerous to use deprecated methods or there is a better way to achieve this.
Like it is described here
In this case you should rather use: parseUri(String, int) to achieve this ( according to the android developer api).

Related

putSerializable for Bundle OK but getSerializable depreciated (passing GregorianCalendar date)

So I'm using the following code to put values into a Bundle
val arguments = Bundle()
arguments.putSerializable(DATE_PICKER_DATE, viewModel.getFilterDate())
dialogFragment.arguments = arguments
getFilterDate() returns a GregorianCalendar.time.
This seems fine but when I unpack the bundle with
val givenDate = arguments.getSerializable(DATE_PICKER_DATE) as Date
It says getSerializable is depreciated.
Can live with this for now but would rather not use depreciates stuff.
Did a load of googling and the simplest way to do this seem to be to use a long to pass the date in milliseconds, which will work for this but does mean some extra date processing but wondered if there is a better alternative to pass complex objects, such as GregorianCalendar dates? Be good to have a nice generic solution. Did look at Parcelables and found https://developer.android.com/guide/components/activities/parcelables-and-bundles but it was not much help. Lacked example code that was useful to me. My search has led me here.
PS
I think the way to put the Date into bundle is
arguments.putLong(DATE_PICKER_DATE, viewModel.getFilterDate().time)
And to get it back to a date is
val givenDate = Date(arguments.getLong(DATE_PICKER_DATE))
Which I guess is a good solution this time but wondering if there is a more generic solution like Serialise.
Whenever you get a deprecated warning, look at the warning to see if there's any information about why it's deprecated and what you're supposed to use instead - or look at the documentation for the method (usually the same thing):
This method was deprecated in API level 33.
Use the type-safer getSerializable(java.lang.String, java.lang.Class) starting from Android Build.VERSION_CODES#TIRAMISU.
So basically, it's telling you to use a new getSerializable method instead, one where you explicitly provide the class of the object being deserialised. So if you're using the Date provided by GregorianCalendar#getTime, you'd do:
val givenDate = arguments.getSerializable(DATE_PICKER_DATE, Date::class.java)
Also note that this is an API 33 (Tiramisu) thing - that means it's not available on lower APIs (so you'd need to use the deprecated method for those, with an API check to work out which to use). It also means it's only just been deprecated, so it will stick around for a while yet - you have the option of just using it! It's your call, but it's unlikely to disappear for a few years.
The other option for this kind of thing is to use a Compat library that calls the relevant method depending on API, handling all the boilerplate for you. I can't see anything for this specific method (although I only checked BundleCompat to see if it was added) but maybe later - it's always worth a look for API-dependent methods though.

How to use method By.clazz from UIAutomator test framework

I'm using UIAutomator test framework for long tests (concerning to my acceptance test). And I need to wait until some activity is started.
I decided to use By.clazz (android.support.test.uiautomator package) methods to find activity object. I expected that something like
uiDevice.wait(Until.findObject(By.clazz(SomeActivity.class)), 30000);
will work. But it doesn't. I suppose that object of my activity cannot be found. I tried to use other By.clazz methods with different params but without success.
So, my code is pretty simple:
UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
/*.... do something...
like click on buttons which will open some activities...
*/
//does not work, time value just for sample
uiDevice.wait(Until.findObject(By.clazz(SomeActivity.class)), 30000);
I found workaround solution with using By.res, like
uiDevice.wait(Until.findObject(By.res(BASIC_PACKAGE, "someMainIdInSomeFragment")), 30000);
But I have very complicated structure of the app with base activities and so on. I often have the same layout for different activities with load different fragments. So I need to know that we started exactly SomeActivity ,regardless of loaded fragments.
So, the questions are:
Is it possible to use By.clazz for Activity to find its object?
Is there some another way to find activity object with UIAutomator?
Did I do everything right? Or maybe there are some mistakes? Is it possÑ–ble to do with UiAutomator?
Thanks!
Using class with UiObject2
Find the EditText, make sure to click on it (legacySetText would do it implicitly), and set your text.
val input = By.clazz(EditText::class.java.canonicalName)
device.wait(Until.findObject(input), TIMEOUT).apply {
click()
text = "your_text"
}
Yes, could be done through the id.
// android:id="#+id/widget_id"
By.res(applicationId, "widget_id")
Your syntax seems good to me. Just make sure no spinner (or any other widget) is blocking your view during the click attempt.

is onActivityResult fundamentally broken?

Some implementations of it, as well as seemingly some devices, seemingly never return RESULT_OK which equals -1, and just return a misleading 0 while including all the necessary data in the Intent extras
I've seen a lot of Google example code simply not do a condition on the resultCode anymore, but they can deprecate it without breaking anything, given Google's propensity to deprecate completely non functional methods because they like their new name more, they could overload a new onActivityResult to simply not have the resultCode as a method parameter.
I was wondering if there is a technical explanation or a blog post for what that particular message passing protocol has seemed to simply fail, without any update in the documentation saying "hey maybe don't rely on the resultCode following any rhyme or reason"
The result code value is a contract defined by the specific activity's implementation. The only contract defined by Android proper is that the result code is an integer.
Android defined simple constants for success (RESULT_OK) and fail (RESULT_CANCEL), but it's up to the activity to decide if it wants to use those, for what purpose, to use different values, or to not even set a result code (in which case the default is RESULT_CANCEL). In many cases, a simple success or fail isn't complete enough and activities return other int values.
So, the short answer is you need to consult the source of the activity to see what it does (or the documentation, but the contract is unlikely to be defined there).

Unable to passing value to another activity in Android

I want to sent value to another activity. I'm using VS 2012 C# for developing apps. I have done lot of search from google. I have tried almost every methods. in my application getIntent(); giving error. that is, getIntent() does not exist in the current context.
I'm also not getting these below functions in my application.
Intent sender=getIntent();
getApplicationContext();
I have added all references. Help me where Am I wrong?
I got answer, I have to use below line of for getting value:
string extraData = Intent.GetStringExtra("KeyName");

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.

Categories

Resources