Access Fragment elements from Activity parent in Android Studio - android

I need to implement in a android app a big form that have 4 sections, so i created 01 Activity with 4 fragments using the ViewPager. Each fragment has some EditText fields. On the 4th fragment, i have the Button to finish the form, so i'd like to click on it and get all the EditText fields.
I think the best solution is to get all of these EditText fields on the MainActivity.java , but when i try to access theses elements from any fragment, I get only this error: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
any idea how to access these elements or any better solution?

Have a shared POJO in the activity, and update it from your Fragment class on every next press.
Read here on how an activity should communicate with fragment
http://developer.android.com/training/basics/fragments/communicating.html
As suggested in the docs you may have an interface for each fragment being implemented by the activity, with the final fragment notifying finish using a boolean value.

I had such a scenario once when creating a survey application.
This is the approach I took:
Create your fragments as needed.
As expected, add your first fragment to your activity.
Important part here - when a user clicks NEXT or Swipes to the next Page, add the answers to a map (each question will map to an answer)
Now repeat this process until you reach the final fragment and simply read out the values (Questions and Answers) from your map.
I found this easier to achieve and gives the expected outcome!
Good luck and happy coding!

Related

How to keep a value from a activity untill app flows starts again

I really don't know how to write the title in the right way, but I will try to explain the issue. I'm working on an app that has like six activities in a sequence, the login is the first activity and once the login is successful I pass the user name to the second activity via bundle and across all the other activities. On the last activity, once the process is successful, it has to go back to the second activity. But, it has to keep the user name. As right now, when the app goes to the second activity, it crashes because it is not getting the user name value, even with the bundle. it is kind of how to make a bundle from two different activities to the same activity.
VERY EASY,
Use viewpager with fragments inside activity instead of Activities(Activities also takes much loading time then fragment)
You can use custom non-swipable viewpager which can be found on google easily.
- Use Viewpager,
- Disable Swiping,
Use click callback on fragments, or EventBus to pass data between activity and fragment.
i would suggest using Eventbus as it a best way for sending and receiving data from-to anywhere.
You can ask me anything more if you are facing any problem.
You have a couple of options to resolve your issue
First Method
Once Login is successful pass in the username using a bundle to the next activity
OnCreate method of MainActivity class retrieve the username
Override the BackPressed method, add a bundle with the username when navigating back to a previous activity to avoid the app from crashing
Second Method
This one is probably less tedious
Use shared preferences to store the username once Login is successful and retrieve the username when needed.
These are two of many ways to solve your problem. Hope this helps

Updating Listview

I am developing an android application similar to Facebook android application. On the timeline screen I have list of posts , user can like or comment any post. When user like a post, to highlight the like button I took the object from array , change its liked status and notify adapter so like button gets highlighted.
If user clicks on a Post a detail screen opens up. In detail screen user also has option to like the post. Now my problem is, if user like a post from detail screen and went back, he should be at the same position in the list and like button of the post on that position should be highlighted.
I tried to do it by starting detail activity with StartActivityForResult() method and passed the selected object. In onActivityResult() method I am getting back the modified object from detail Activity. I replaced the original post object by the modified object in array and notify the adapter.
I am not sure about my logic that its a good one or not. I need a better solution to do this. I will be very thankful to any good suggestion.
onActivityResult() would be just the right answer but you are not finishing your activity but pressing back/home button instead. So in this case no information is being passed to the parent activity.
A solution that comes to my mind is modifying your objects more permanentle via sharedPreferences or some ORM. But it may be something unpleasant being collecting data from memory in every movement of your app.
What I suggest is transforming your detailActivity to a detailFragment. It would be easier to pass information to the parent activity. In this case the activity that has the full list would start the fragment passing the single element that has been clicked. After that, you would implement a interface to comunicate with the parent activity and in this case the main list would always be updated correctly.
This method requires a very long explanation, too much in fact. I would point out the main steps in order to give a starting point for researching.
Create a fragment similar to your detailActivity. It needs a declaration of the proper interface to communicate with the activity.
Make your activity to implement the interface and override its definition. This function will handle like button being pressed. So is it here where you need to update the main arrayList.
Change one main fragment with detail fragment when an item is clicked.
I hope it helps you to find final solution for your code.
PD: I found this url that may content the whole process, just very well detailed.
Yes. onActivityResult() is a good implementation for activity to activity communication.
Your logic is not wrong.
But if you want it to be simple, you might want to try some third part library like EventBus, it could help you to deliver your message between components like activities easily.
In your case, a StickyEvent is helpful.

Handling dependent data between tabs in tabbed activity

I'm currently trying to switch my Android application from individual activities to fragments contained in a single tabbed activity, however, I'm running into some snags with figuring out how to pass data between them. I was originally just using intents. However, now that I'm using fragments, I'm currently storing any data I need as a field variable in my tabbed activity (As this answer outlines). I'm getting null pointer exceptions because my tabbed activity is attempting to load my first and second fragment, but my second fragment depends on a EditText value from my first fragment. Is there any way I can load these fragments one at a time, and pass my field data (and load my second fragment) when the user swipes? If there is a way, is this the best way of solving my problem? I'm very open to other suggestions. Thanks guys!!
There is a special dedicated topic for this here http://developer.android.com/training/basics/fragments/communicating.html.
I would declare two interface one in each fragment. Then implement the interface in the activity. On EditText change in the first fragment send the value to the activity and store the value in the activity in a instance variable. Then on the second fragment retrieve the value in the second activity from the activity.

Passing data between Fragments and saving state on Screen Orientation Change

Before I begin, I have read this, this and some more articles online. I am still unable to find a right way to do it.
So I have just one activity in my App, and 6 fragments. First one is a ListFragment which loads a list from a SQLite table. When user taps on a row in this list, I do 2 things:
1) Get an int from that row through a listener, and pass it back to the parent activity which stores it as a class variable using a simple setter method.
2) Replace this ListFragment with another simple Fragment. This new Fragment uses a simple getter() on that class variable to retrieve some information from a different table, and show all the details to the user.
So far so good. Now if I am on this details Fragment, and I change the screen orientation, the activity state is not reloaded (as I am checking if savedInstanceState is null in the onCreate()), but however, the class variables lose their value, and my app crashes.
Basically I am trying to pass data from the ListFragment to the details Fragment. I am doing it through the activity, which is causing a problem. As per Android Documentation:
All Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
There is no specific code which is giving me trouble, so didn't post any.
The onSaveInstanceState and onRestoreInstanceState is only used to save and restore per-instance state of an activity in case your activity is destroyed by OS (for example, to free the memory or in order to recreate it when the device orientation was changed). So you can save your variable in onSaveInstanceState and get them back using onRestoreInstanceState.
For your next question, I think this article will help you. Also answer by Gene for this question will help you.

Android : Accessing container activity object from fragment using putExtra?

I am building a tab interface using Action bar and fragment. I would need assistance in sending data from container activity to the fragment.
To elaborate, I have job object in container activty. And I have created few tabs based on the information in job object (like company details, experience details etc). I need to pass the job object to these fragments so that it can display respective information.
I have created container activity and tab fragments. I would need an example on how to pass the object across them. I cannot use intent.putExtra. Can I access parent container's object from fragment?
Any help shall be appreciated.
Thanks.
Make the method in your activity, e.g getJob that will return the Job object and its information
MyActivity extends Activity{
Job mJob;
public Job getJob(){
return this.mJob;
}
}
then in your Fragment you do this:
MyFragment extends Fragment{
#Override
public void onActivityCreated(){
super.onActivityCreated();
((MyActivity)this.getActivity()).getJob();
}
}
use getActivity and the method getJob(); to get the object
There are multiple ways of achieving this.
Make a static variable to hold your data and access that data from inside the fragments - this is the most fast but it creates bad design patterns if used improperly.
A way of Fragment-to-Fragment communication possible through the parent Activity is posted here: http://developer.android.com/training/basics/fragments/communicating.html You can use the sample code to just do a Activity - Fragment data send.
The top voted answer here: Accessing instance of the parent activity? mentions a way to avoid using static data (1.) and contains source code examples using ActivityGroup
"If you need access to some values in your First activity without
making a static reference to it, you could consider putting your
activities in an ActivityGroup."
What you choose is your preference, these are just a few options!
Edit: I'm not sure if number 3 will work with fragments since I haven't tested a method similar to it, the example is Activity - Activity communication.

Categories

Resources