Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: getIntent() is deprecated

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:

  1. Can I make intents work for this purpose still? What should I do to get around this deprecation issue?
  2. 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.
like image 210
rnbee Avatar asked May 31 '15 15:05

rnbee


2 Answers

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();
like image 60
Keyur Nimavat Avatar answered Oct 11 '22 15:10

Keyur Nimavat


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 deprecated
Intent 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).

like image 25
anuragsinhame Avatar answered Oct 11 '22 15:10

anuragsinhame