How we get the previous data of fragment in android? - android

In my application Main_Activity contain four fragments. In one fragment (called mobile_fragment) whenever i click the button in fragment it will move to another activity, in that i need to get the one value and need to send that data to that fragment(mobile_fragment).
what i done is:
whenever i click the button in fragment i moved to activity and get the value and that value sent to main_Activity, after that in mobile fragment i accessed that variable (static declaration of variable in main_activity).
Now my problem is after getting the value in mobile_fragment, i already entered values in remaining edit text widgets are cleared (no text). how i get previously entered values?
please any one help me.
fragment
public class Mobile_Fragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null) {
return null;
}
browseplans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), BrowsePlans_Activity.class);
startActivity(intent);
}}
BrowseplansActivty:
Intent intent=new Intent(BrowsePlans_Activity.this,MainActivity.class);
intent.putExtra("Amount",amount);
startActivity(intent);
Main_Activity:
public class MainActivity extends FragmentActivity implements OnClickListener {
public static String TAG = "Main First Frag";
public static String contact_number, prepaid_amt;
Fragment fragment;
FragmentManager frgManager;
FragmentTransaction ft;
Bundle b = new Bundle();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initUI();
bindEvents();// now this is my changed one
Intent in=getIntent();
prepaid_amt=in.getStringExtra("Amount");
Log.v("TAG+AMOUNT",""+prepaid_amt);
}
}

To pass data from your fragment to the Activity you are starting, pass it through Intent Extras.
To return data from the Activity back to the fragment, call setResult with a result code and an intent that, again, holds data set with extras. Retrieve that data in the onActivityResult override of your fragment.
To save information in a fragment when it is detached and then re-attached, use the override onSaveInstanceState and then extract data from that state in onCreate and/or onCreateView overrides.

Related

OnBackPressed() brings back incorrect activity

Within my Main_Activity, I have a Button which when OnClicked opens the new Game_Activity, within the OnCreate of my Game_Activity I have:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_true_false);
level1GameInstructions = new Level1GameInstructions();
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.game_activity, instructions).commit();
}
Which opens a Fragment, then within the Fragment class when a Button is clicked i want to close the current Fragment open so I have done this:
View.OnClickListener playBtnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
};
However, for some reason this returns the Main_Activity rather than the Game_Activity. Does anyone know why?
Be glad to use these two methods instead of your code:
public void removeFragment(#NonNull String tag) {
getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentByTag(tag)).commit();
}
public void replaceFragment(#IdRes int containerId, Fragment fragment, #Nullable String tag) {
getSupportFragmentManager().beginTransaction().replace(containerId, fragment, tag).commit();
}
Just replace the needed fragment with some tag, and remove it by that tag.

Android buttons' onClickLIstener() only works once when the Activity begins, not when returning from Fragment transaction

Any time the main Activity is started or restarted (i.e. by pressing the home button on my action bar), all of the buttons (which reside in a fragment in this main activity) work correctly. However, if I press one of the buttons, then press the back button, the home fragment and its buttons reappears but none of the button callbacks work. The button images continue to change appearance when pressed, as always.
The callbacks are assigned in the onCreateView method of the home fragment, as follows:
public class HomeFragment extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Button button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d(TAG, "Button!");
mActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.contFragMain, new SomeFragment())
.addToBackStack(null)
.commit();
}
});
}
Here is the superclass of Fragments I launch with the buttons:
public abstract class RouteListFragment extends SherlockFragment {
private static final String TAG = RouteListFragment.class.getName();
private Activity mActivity; // parent activity
RouteListAdapter mAdapter;
ListView mListViewRouteList;
public RouteListFragment() {
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bndl = getArguments(); // data passed should contain search term
View v = inflater.inflate(R.layout.fragment_route_list, container, false);
mListViewRouteList = (ListView) v.findViewById(R.id.listViewRouteList);
addRoutesToList(); //Populates the list with data via an async DB call
return v;
}
You shouldn't be stashing the Activity reference; the Activity is probably getting recreated at some point (depends on how your flow is), but you should either reassign the reference in onAttach (Activity activity), or just call getActivity() to get the currently Activity you're attached to.
So mActivity.getSupportFragmentManager()...
should instead be
getActivity().getSupportFragmentManager()...
EDIT: Wait, maybe that's not right. What is v in onCreateView()? You're not creating any UI in this Fragment? You should be using onViewCreated() to get a reference to the views in the created hierarchy.

using bundle to pass data between fragment to another fragment example

I have 3 sherlockListFragments in my app. Every fragment has some editTexts and the last fragment has a button which when it's pressed all data in the first and second fragments should be accessed and stored.
I used bundle to send data between fragments. with the simple following example,
This is the code of my first fragment :
public class PersonalDataFragment extends SherlockListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragmet_personal_data, container, false);
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
PersonalDataFragment fragment = new PersonalDataFragment();
Bundle bundle = new Bundle();
bundle.putString("y", "koko"); //any string to be sent
fragment.setArguments(bundle);
super.onCreate(savedInstanceState);
}
}
and this is the code of the fragment that receives the text :
public class WorkExpRefFragment extends SherlockListFragment {
String myInt;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_workexp_ref, container, false);
final EditText t = (EditText) view.findViewById(R.id.editText5);
final Button generate = (Button)view.findViewById(R.id.button2);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
t.setText(myInt + "sadfigha");
}
});
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
if(getArguments()!=null) {
myInt = getArguments().getString("y");
}
super.onCreate(savedInstanceState);
}
}
Now I have a null in the third fragment, what should i do ?
Thanks in advance
It's normal that your code fails. In the first fragment all you do is create a new instance of PersonalDataFragment and you pass it a Bundle with the data. The problem is although fragment holds the data in the Bundle, the fragment itself is not the one used by the app(isn't even attached to the Activity). You also set the Bundle on a PersonalDataFragment instance but you try to access the data in a WorkExpRefFragment which will obvious not work as the two fragments don't have a direct connection.
One simply solution for what you want to do is to let the Activity "save" the data for your fragments as the Activity is available for all fragments. First create two methods in the Activity holding the three fragments:
public void saveData(int id, Bundle data) {
// based on the id you'll know which fragment is trying to save data(see below)
// the Bundle will hold the data
}
public Bundle getSavedData() {
// here you'll save the data previously retrieved from the fragments and
// return it in a Bundle
}
Then your fragments will save their data like this:
public class PersonalDataFragment extends SherlockListFragment {
// this will identify the PersonalDataFragment fragment when trying to save data
public void static int id PERSONAL_ID = 1;
//...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = new Bundle();
bundle.putString("y", "koko"); //any string to be sent
YourActivity activity = (YourActivity) getActivity();
activity.saveData(PERSONAL_ID, bundle);
}
}
To retrieve the data in the WorkExpRefFragment fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
YourActivity activity = (YourActivity) getActivity();
Bundle savedData = activity.getSavedData();
}
Depending on how you used those fragments this solution might not work. Also, keep in mind that the Bundle you pass like above will not be retained for a configuration change.

Updating ListView (in Fragment) after Dialog dismiss

I've read some question about this kind of problem but i can't solve it.
I've had this:
public class Classwork extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homework);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
args.putInt("posizione", position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
//code for number of pages
}
#Override
public CharSequence getPageTitle(int position) {
//code for return the title
}
}
public class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//query to populate ListView
//ListView with CustomAdapter
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
//Start new activity DialogDeleteAddGradeCopy
}
});
myDbHelper.close();
return rootView;
}
}
}
I've created it with the Eclipse wizard.
A DummyFragment contains a ListView, that is populated (correctly) with a SQLite query.
With a click on an item of the ListView a "dialog" (actually is an activity with a dialog style) is displayed.
Dialog:
public class DialogDeleteAddGradeCopy extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//retrive data form Intent for the update in the db
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//update the db
finish();
}
}
});
}
This dialog allows the user to update (with db query) one of the values of the clicked item.
All is working fine, except the update of the Fragment. The update query is ok (db is up-to-date when the dialog is closed), but to update the Fragment i need to swipe right or left two times and turn back (in this way the fragment is re-created so all works fine).
How can i force updating/re-creating the Fragment?
Thanks in advance.
Sorry for my bad English...
Normally when using multiple instances of Fragment (which I'm guessing you are based on the swipe left/swipe right comment) you don't want to update the content using an Intent as you would with an activity but using an Interface.
If the data is coming from another Fragment hosted by the same activity, say in a ViewPager or tab set up, you would set up an interface between the information sending fragment and the host activity and then call a public method to update the reciving fragment from within the host activity. The basics of using an interface to update fragments can be found here. I don't know the specifics of your whole project but I'd look into this.
As for what's posted:
You're code is not behaving properly because getItem is not proper in this context. When you are updating information by passing an intent and need to retrieve a new Bundle of information you should use
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
}
You may have to set an activity flag to get this to work (for example FLAG_ACTIVITY_SINGLE_TOP) but basicly the idea is onNewIntent will be updated when a new intent is passed to your activity. Using getItem as you have it now will only update when the fragment is initially created and the args are set.

how to pass the data in between activity to fragment using bundle in android

I can store the value in one variable. Now I want pass that variable into a fragment
Using the code below, I am able to load fragments:
public class AndroidListFragmentActivity extends Activity {
Fragment2 f2;
public static String itemname;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apetiserfragement);
itemname=getIntent().getStringExtra("itemname");
Bundle args=new Bundle();
args.putString("itemname", itemname);
f2=new Fragment2();
f2.setArguments(args);
}
} /* (Here I load fragment using xml page) itemname */
The output is splitted into 2 windows one for extend for listfragment (for listview) and one for fragments.
Fragment2.xml
public class Fragment2 extends Fragment {
String itemname;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
System.out.println(getArguments().getString("itemname"));
return inflater.inflate(R.layout.fragment2, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
}
AndroidListFragmentActivity in this class itemname I want pass Fragment2.class.. please help me
If both fragment are on other activity then can use intent
if on same activity then can do operation on that particular activity
as in this link
see onListItemClick of class TitlesFragment
**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {//<---------------------f on same activity then can do operation on that particular fragment
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment) //<------------------------see use getFragmentManager
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else { //<----------If both fragment are on other activity then can use intent
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
See this response here : data sharing between fragments and activity in android

Categories

Resources