Value in the Fragment cannot be shown - android

I have a typo regarding getting value from bundle and show it in the Fragment.
My song class has two values title and its detail.
private String songTitle;
private String details;
After sending value from bundle in Adapter part, I get it from Detail Part by doing vice versa process. I show it via getSupportFragmentManager feature.
Although the detail page open without any problem, there is no value in Detail part.
Here is my Detail part and Fragment part.
How can I fix it?
Detail Part
if (savedInstanceState == null) {
// Get the selected song position from the intent extra.
int selectedSong =
getIntent().getIntExtra(SongUtil.SONG_ID_KEY, 0);
Log.i(LOG,"selectedSong : " + selectedSong);
// Create instance of the detail fragment and add it to the activity
// using a fragment transaction.
SongDetailFragment fragment =
SongDetailFragment.newInstance(selectedSong);
getSupportFragmentManager().beginTransaction()
.add(R.id.song_detail_container, fragment)
.commit();
}
Detail Fragment
public static SongDetailFragment newInstance (int selectedSong) {
SongDetailFragment fragment = new SongDetailFragment();
// Set the bundle arguments for the fragment.
Bundle arguments = new Bundle();
arguments.putInt(SongUtil.SONG_ID_KEY, selectedSong);
fragment.setArguments(arguments);
return fragment;
}
Link : Project Link

I solve it by defined static methods for list process in which items are inserted

Related

Sending data to Fragment of Fragment from Activity (Activity->Fragment->Fragment) on menuItemclick

I am trying to send a data from MainActivity (on MenuItem click) to a Fragment of its Child Fragment.
I have shown an image to understand better.
I want an event to be fired in DayFragment from the MainActivity when MainActivity menuclicked.
I cannot send when the fragment is being created as you know.
Any ideas (or) code to understand the idea would be helpful.
Guys, Negative vote would neither help you nor me.
I will explain in little detail.
I am going to show a datepicker dialog fragment on menu item click on MainActivity. I need to pass the date from MainActivity -> calendarfragment - > dayfragment.
I want the date in dayfragment to other process. Thats it.
Create a public method inside Fragment which the Activity will call upon item selection.
From that public method, using the instance of ChildFragment, call another public method inside ChildFragment to make the magic happen!
You can use Fragment.setTarget(Fragment fragment, int requestCode); , just in case
Use a Bundle. Here's an example:
Fragment fragment = new Fragment(); // replace your custom fragment class
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager(). beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();
Bundle has put methods for lots of data types.
Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}

Check which Activity loads a fragment

Is there a way to check which activity loads a fragment from within the fragment? I have a user profile fragment which is loaded from 2 different activities but only one passes a value in, so when getting values from the bundle when the fragment loads from the activity that doesn't pass a value throws a nullpointerexception. Or is there a better way to pass the value into the fragment so the fragment can get the value only when loaded from this specific activity?
You can simply do this check in your fragment:
if(getActivity() instanceof SomeActivity){
//do something
}
You can also cast the getActivity() call if you are sure which Activity it is (and then call methods from that Activity).
You can define two static methods (also known as Static Factory Methods) which returns instances of your Fragment with the parameters you want to pass with bundle like the following code:
private static final String BUNDLE_VALUE_KEY = "value";
#NonNull
public static YourFragment newInstance() {
return new YourFragment();
}
#NonNull
public static YourFragment newInstance(#NonNull String yourValue) {
final YourFragment instance = new YourFragment();
final Bundle args = new Bundle();
args.putString(BUNDLE_VALUE_KEY,yourValue);
instance.setArguments(args);
return instance;
}
In your Activity which you want to pass the value you can use:
final YourFragment fragment = YourFragment.newInstance(value);
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
In other Activity you can use:
final YourFragment fragment = YourFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
And in onCreate method of your Fragment you can check arguments and init your value like the following code:
final Bundle args = getArguments();
if(args != null){
yourValue = args.getString(BUNDLE_VALUE_KEY,null);
}
So if your Fragment is attached to the Activity which passes data you'll have it. If the Fragment is attached to other Activity you'll have the initial value (in the example it's null)
Or you can check the instance of Activity which Fragment gets attached. (Not best practice)
if(getActivity() instanceof YourActivityWhichPassesData){
yourValue = getArguments().getString(BUNDLE_VALUE_KEY,null);
}

How to parsing in a fragment?

I made an application which has an Activity that parses a XML file (XMLPullParser) and shows data in a Listview. It works.
In the same application I have another Activity in which I put different fragments in dependece of the selected item of the Navigation Drawer.
Now, my question is: how can I use the data, obtained in the Parsing activity, and manage them inside a fragment?
You don't have to send the whole parsed data to the fragment.
You can write an own Handler or Manager class to parse the file for you and keep it in the memory (It can be some Singleton stuff). Once you parsed it you just have to pass the ID of the item and the Fragment can get it out from your Handler.
You can pass whatever you like to the Fragment like this:
public static YourFragment newInstance(int index) {
YourFragment f = new YourFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
//To get out
//...
Bundle args = getArguments();
int index = args.getInt("index", 0);
//...

Android studio passing data between 2 fragments! Getting an error

I have 2 fragments, which are being replaced in a container inside the main activity layout. One fragment passes the data through an interface whenever clicking on the button. When I click the button, I want my first fragment to be replaced with the second fragment, in the same container. However, I have an issue...
In the second fragment, I need to get the data and use it on a view. Now, in the second fragment, I have a method for getting the data. In the activity, I know that I need to find the ID of the second fragment in order to use its method. However, this fragment doesn't have any ID (because I'm going through fragments by code). Since I can't find the ID of the fragment, I'm getting an error and I can't pass the data to the second fragment.
How to solve this? Can it be solved?
Thank you very much!
You can get the fragment by ID if you have it in XML layout.
If you are handling your fragment in code, you can use a TAG and find it by that.
Starting a fragment
String FRAGMENT_TAG = "myFragment";
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().add(R.id.container, new MyFragment(), FRAGMENT_TAG).commit();
Getting the fragment by TAG
MyFragment fragment = (MyFragment) manager.findFragmentByTag(FRAGMENT_TAG);
if (fragment != null) {
fragment.passData(data);
}
You should define a static constant for fragment argument and then call newInstance from second fragment to initialize first fragment and passing data from 1 to 2
Below code is example of above description:
private static final String ARG_DATE = "date";
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(ARG_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
to retrieve/resolve DatePickerFragment argument data:
Date date = (Date) getArguments().getSerializable(ARG_DATE);
to initialize Fragment in another xxxFragment(that's mean pass the crime's date data from xxFragment to DatePickerFragment):
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
you can check out my github repository to understand %100
[https://github.com/Zfr21/CriminalIntent/commit/2ed69c056988818f6f6423762c97a6bf1a82b547][1]

How to update the content of a TextView in a fragment in navagation drawer in Android

I'am new to Android application developpement. I'am trying to create an application using navigation drawer. I created an apllication with the navigation drawer template with android studio. Then i changed it to redirect the user to a new fragment_layout each time he chooses a new item in the navigation menu. Now, my first fragment contains a listview, and onclick on one item of the list i am redirected to a detailfragment which contains a TextView.
When i tried to populate this TextView with details of the selected item i had a null pointer exception.After two days of research and trying to find out what is the problem i discovered that my visible fragment returns false when i call fragment.isInLayout().
Thanks for your help.
My code :
Creation of a new fragment :
VideoDetailFragment fragment = new VideoDetailFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title)
fragment.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
getFragmentManager().executePendingTransactions();
if (fragment.isInLayout()) {
fragment.replaceText("Lalala");}
And the method replaceText code is :
public void replaceText(String text){
textView.setText(text);
}
The problem is that the methode replaceText is not reached And when i remove the if statement a null pointer exception is raised saying that i can not write in the textView
EDIT: I think the problem is with transaction.replace(R.id.container,fragment);, maybe there is another alternative to replace a fragment_layout content. Because, i have the VideoDetailFragment displayed in the simulator and i can't change it's content, Also when i tired VideoDetailFragment fragment1 = (VideoDetailFragment)getFragmentManager().findFragmentById(R.id.container);
it gave me a cast exception.
Thanks a lot for your help, really need it :)
Try to do something like this:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(key, value);
fragment.setArguments(bundle);
Then in your second Fragment, retrieve the data (you could do it for example in onCreate()) with:
Bundle bundle = this.getArguments();
int myString = bundle.getString(key, ""); //the second parameter is a default value
Or show your code to see where do you get NullPointerException
YourFragment fragment = getSupportFragmentManager().findFragmentById(R.id.your_fragment);
if (fragment != null) {
fragment.yourUpdateDataMethod(youData);
}

Categories

Resources