Fragment over Fragment issue - android

My requirement is :
In one Fragment, had textview, by clicking on that one DialogFragment is appearing with a list of values. By clicking on value, The dialog fragment should be closed and selected values should be displayed in textview in the first fragment.
But here the problem is accessing textview object is null.
Communicating between fragments using interface i.e., By clicking on list in dialogFragment one interface is calling. That interface method implemented in first fragment.
So, How to access the textview object?
Here code is:
FragmentManager manger = getFragmentManager();
listDialogFragment.show(manger, null);
public interface onOkClickListener {
void setOnOkClickListener(int pos,String selectedID,MainActivity actv);
}
#Override
public void setOnOkClickListener(int pos,String id,MainActivity actv) {
textView object// accessing null
}
Thanks In advance..

Related

Updating listview fragment on viewpager tab changes

I have a ViewPager using a FragmentPagerAdapter for displaying three tabs, each represented by its ow fragment. One of these fragments contains a list, that should be updated on switching / swiping to that tab. But I don't find any way to make it happen. I tried using the onResume method, but the fragments seem not to be paused and resumed on tab change. I also tried using ViewPager.OnPageChangeListener in my MainActivity:
#Override
public void onPageSelected(int position)
{
FragmentRefreshInterface currentFragment = (FragmentRefreshInterface) mSectionsPagerAdapter.getItem(position);
currentFragment.onRefreshed();
}
And in the fragment I use the following:
#Override
public void onRefreshed()
{
List<Record> records = mRecordingService.getRecords();
mRecordAdapter.clear();
mRecordAdapter.add(record);
}
But using this code I can't access my RecordingService class that is used to provide the database functions (because mRecordingService seems to be null). I initialize it in the fragment like this:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mRecordingService = new RecordingService(getContext());
}
Using the onPageChangeListener is the correct way to do it. I believe the reason why your code is not working, is because you are calling getItem on your pager adapter: getItem() actually returns a new instance of the fragment. In order to get the current instance, you use instantiateItem() (which returns a reference to the fragment actually being used).
Change your code to look something like this:
#Override
public void onPageSelected(int position)
{
FragmentRefreshInterface currentFragment = (FragmentRefreshInterface) mSectionsPagerAdapter.instantiateItem(viewPager,position);
currentFragment.onRefreshed();
}
And it should work.
I suggest that the code you have in onRefreshed() go in onResume() instead. Fragment doesn't have an onRefreshed() method. You must be implementing another interface that declares this method.
Since you are storing data in a database, you should be use a CursorAdapter or subclass such as SimpleCursorAdapter. If you do this correctly, the ListView will automatically update when you add a record to the database. Then the service can add records without needing to access the service from the fragment.
In your MainActivity:
private FirstFragment firstFragment;
private WantedFragment wantedFragment;
private ThirdFragment thirdfragment;
In getItem
switch(postition){
//return first, wanted, third fragments depending on position
}
onPageSelected:
if(position == 1) // position of the wanted fragment
wantedfragment.onRefreshed()

Passing ListView to another Listview

I have listview in one fragment that displays item from a sqlite database. When I click on one item it opens a menu to allow to open, add to another listview or delete. I want to be able to add it to another listview in another fragment on press. I tried adding it to another listview using bundles but I had no luck. I have a plan of creating another database table to store the added data and display it in a new listview. Would this work? or do any of you guys have another suggestion?
You can send data from one fragment to another. The best way to do this is by going through the parent activity. Something like this:
public class MyActivity extends FragmentActivity implements MyFragmentListener {
MyFragment1 frag1;
MyFragment2 frag2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(0);
FragmentManager fm = getSupportFragmentManager();
frag1 = (MyFragment1) fm.findFragmentByTag("frag1");
frag1.setListener(this);
frag2 = (MyFragment2) fm.findFragmentByTag("frag2");
}
// Call this function from frag1 when you want to send the data to frag2
public void addToFrag2(ListItem item) {
frag2.addToList(item);
}
}
// Define whatever methods the fragments want to use to pass data back and forth
public interface MyFragmentListener {
void addToFrag2(ListItem item);
}

Dialog-fragments getView() returns null when called from outside

I have a problem when trying to access my dialogs fragments view.
Here is what I do:
For each button in my main activity I create a new dialogFragment when the button is clicked:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment newFragment = ResAmountDialog.newInstance(R.string.res_dialog_title);
newFragment.show(getFragmentManager(), "dialog");
ImageView resIcon = (ImageView) newFragment.getView().findViewById(R.id.resourceIcon1);
resIcon.setImageResource(currentResourceImage);
}
});
The dialog fragment consists of an EditText and ImageView. I'm trying to access the imageView in the above code by getting the fragment, then its view and then finding it by ID, but it returns null.
I tried to find a solution on the internet but all the similar problems had their views accessed within the fragment, i try to access it from outside.
A Fragment's view is not loaded until its onCreateView() method is invoked (see the Fragment lifecycle: http://developer.android.com/guide/components/fragments.html). You really shouldn't try to update a Fragment's view like you are trying to. Set the image inside your Dialog Fragment's onCreateView() instead. Use setArguments() and getArguments() to pass a specific resource ID (see passing argument to DialogFragment).

how to get the value of another fragment that its not the current in an activity

i got a problem while working with fragments, in the first fragment i got a textview, ie:
<EditText
android:id="#+id/LeyOrdenanza"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="#dimen/dpde10"
android:ems="10"
android:hint="Ley / Ordenanza"
android:textColor="#color/cafeoscuro"
android:textColorHint="#color/cafeclaro"
android:textSize="#dimen/legra25" />
the user puts a value, then i change of fragmet, in the new fragment i got a button that calls a function in the class that contains the fragments like this :
EditText LeyOrdenanzav = (EditText) findViewById(R.id.LeyOrdenanza);
LeyOrdenanza = LeyOrdenanzav.getText().toString();
but i get null, when i put the button with the function on the same fragment, everything works like a charm, but i need to change that button to the second fragment, thats when it stops working, any suggestions?...
Hi i hope i got your question right,
in order to send data between fragments you need to create an interface communicator as follows, I'll suggest to make a new class so not to confuse yourself.
public interface Communicator {
public void getData(String data);
}
Have your MainActivity Implement Communicator as follows.
public class MainActivity extends ActionBarActivity implements Communicator
after implementing the communicator add the umimplemented method which is getData in the form String in your Case.
this method will work as a hub between the two fragments.
Create an Instance of the Communicator in the fragment where you get the String from the TextView
Communicator communicator = (Communicator) getActivity();
Now Pass the String Like this communicator.getData(StringtToPass);
Initialize an instance of the Fragment in the method using Fragment Manger
FragmentManager fragmentManager = getFragmentManager(); fragmentTwo fragmentTwo = (fragmentTwo) fragmentManager.findFragmentById(R.id.fragmentTwo);
On the Other fragment create a method similar to this
public void setData(String string) {
textView.setText(stringPassed);
}
After you initialize the Fragment in the MainActivity you can pass the data this way.
fragmentTwo.setData(StringToPass);
Hope this will help a little.

update TextView in fragment A when clicking button in fragment B

I have two fragments sitting side by side in the same activity. When I touch a button in the right fragment (fragment B), I need a TextView in the left fragment to update (fragment A). I have looked all over for the best way to do this, but nothing seems to work for my needs. Could someone possibly give me an example of how I would code this? Fragment A is set through the XML layout, and fragment B gets loaded programmatically into a container. I have tried accomplishing this by using a method in fragment A to update the text, and calling on that method from a method in the parent activity. I then call on the method in the parent activity from fragment B.
This is the code in fragment B that declares the interface and calls a method in the interface
AttackCards attackCards;
public interface AttackCards {
public void deckSize();
}
public void onAttach(DeckBuilder deckBuilder) {
super.onAttach(deckBuilder);
attackCards = (AttackCards) deckBuilder;
}
attackCards.deckSize(); //this is in my onclick methods
This is the code in the activity that implements the interface and calls the method in fragment A
public class DeckBuilder extends Activity implements AttackCards{
public void deckSize() {
DeckBuilderFragment deckBuilderFragment = (DeckBuilderFragment)getFragmentManager().
findFragmentById(R.id.deckbuilder_fragment);
deckBuilderFragment.deckSize();
}
This is the method in fragment A that appends the textview with the contents of a shared preferences value
public void deckSize() {
deckSize = (TextView) getView().findViewById(R.id.decksize);
final SharedPreferences defaultDeck = getActivity()
.getSharedPreferences("defaultDeck", Context.MODE_PRIVATE);
deckSize.setText(String.valueOf(defaultDeck.getInt("decksize", 0)));
}
Sadly this attempt simply brings me a nullpointer when touching a button. I am getting a null pointer at
attackCards.deckSize(); //this is in my onclick methods
Could someone please help me out with an example of how to do this correctly?
One fragment should not communicate to another fragment directly. It should do so through attached activity. The detail explanation with code example is available here
Android Developer site
Declare an interface in Fragment B, and implement the interface in the activity. Call the interface through callback in Fragment B when button is clicked. You can have a public function in Fragment A to update the TextView, so activity directly call the function to update the text.
You can define an interface in Fragment B and implement it on the MainActivity. Then on the callback method (onClickOnB in this case) set the text on the TextView. You should obtain a reference of the TextView in the Activity's onCreate() after setContentView(). This works because Fragment A is static. Otherwise, you can create a public method inside Fragment A so you can set the text from inside the callback by getting a reference of Fragment A and calling such method.
Fragment B
public class FragmentB extends Fragment implements onClickListener{
ClickOnB listener;
public void setOnFragmentBClickListener(ClickOnB listener){
this.listener = listener;
}
#Override
public void onClick(View v){
//stringMessage is a `String` you will pass to `Fragment` A to update its `TextView`
listener.onClickOnB(stringMessage);
}
interface ClickOnB{
public void onClickOnB(String message);
}
}
MainActivity
public class MainActivity extends Activity implements ClickOnB{
#Override
protected onCreate(Bundle savedInstanceState){
//Get a reference of `Fragment` B somewhere in your code after you added it dynamically and set the listener.
((FragmentB)getFragmentManager().findFragmentByTag("FragmentB")).setOnFragmentBClickListener(this);
}
#Override
public void onClickOnB(String message){
//Set the text to the `TextView` here (I am assuming you get a reference of the `TextView` in onCreate() after inflating your layout.
mTextView.setText(message);
}
}

Categories

Resources