Hey I'm trying to add an onSharedPreference Listener into n Fragment. It should regulate if a change is done (switch in the settings) the value of the NumberPicker inside the Fragment changes(0 or 1) too.
the problem with the listener: it only works the first 5-10 times then it doesnt get called anymore (i suppose)? -> no changes done on NumberPicker
following the importants code of my fragment:
public class FragmentTwo extends Fragment {
private EditText mEnterWeight;
private NumberPicker mUnitPicker;
private TextView mConverted;
private int pick;
private String convertedWeightMessage;
private Double enteredWeight;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mEnterWeight = (EditText) view.findViewById(R.id.WCenterWeight);
mUnitPicker = (NumberPicker) view.findViewById(R.id.WCunitPicker);
mConverted = (TextView) view.findViewById(R.id.WCconverted);
initialiseUnitPicker();
//some stuff
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
if(key.equals("SwitchMainUnit")) {
Boolean kg = prefs.getBoolean("SwitchMainUnit", true);
if(kg)
mUnitPicker.setValue(0);
else mUnitPicker.setValue(1);
}
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
return view;
}
The docs say that i need to change the onResume() and onPause() to:
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
But where do i need to add these? Got errors when i tried to add it in the Fragment.
Thanks for helping; didnt come to any solution myself.. :/
The documentation says
Caution: When you call registerOnSharedPreferenceChangeListener(), the
preference manager does not currently store a strong reference to the
listener
I recommend that you store your instance of SharedPreferences.OnSharedPreferenceChangeListener listener as a field outside of onCreateView.
Example code:
public class FragmentTwo extends Fragment {
private EditText mEnterWeight;
private NumberPicker mUnitPicker;
private TextView mConverted;
private int pick;
private String convertedWeightMessage;
private Double enteredWeight;
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
if (key.equals("SwitchMainUnit")) {
Boolean kg = prefs.getBoolean("SwitchMainUnit", true);
if (kg) mUnitPicker.setValue(0);
else mUnitPicker.setValue(1);
}
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mEnterWeight = (EditText) view.findViewById(R.id.WCenterWeight);
mUnitPicker = (NumberPicker) view.findViewById(R.id.WCunitPicker);
mConverted = (TextView) view.findViewById(R.id.WCconverted);
initialiseUnitPicker();
//some stuff
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs.registerOnSharedPreferenceChangeListener(listener);
return view;
}
Related
I'm having difficulties with making my app persistent. When I rotate my phone the data on the screen doesnt change. But after I click on a button to retrieve a new fragment I get an error saying "Can not perform this action after onSaveInstanceState". I have googled and seen similiar problems but I still dont know how to approach and solve this.
I have an activity class, a controller class and two fragment classes.
The activity class has a navigationviewer with 2 buttons that triggers a fragmenttransaction. That is, on each button click it will replace the current fragment with the one set in the button listener. My controller class initalizes the system and the fragments are just the UI.
My activity class:
public class LoggedInActivity extends AppCompatActivity {
private final String TAG = "LoggedInActivity: ";
private Controller controller;
private TextView navName;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
if(savedInstanceState == null) {
Log.v(TAG, "savedInstanceState == null");
initComponents();
setNavName();
initListener();
initializeSystem();
} else {
Log.v(TAG, "savedInstanceState != null");
initComponents();
setNavName();
initListener();
this.controller = (Controller)savedInstanceState.getSerializable("controller");
}
}
private void initComponents() {
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View headerView = navigationView.getHeaderView(0);
navName = (TextView) headerView.findViewById(R.id.tv_name_surname);
}
private void initListener() {
navigationView.setNavigationItemSelectedListener(new MyNavigationItemListener());
}
private void initializeSystem() {
Log.v(TAG, "new controller");
controller = new Controller(this, null);
}
public void setFragment(Fragment fragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container_logged_in, fragment).commit();
}
private class MyNavigationItemListener implements NavigationView.OnNavigationItemSelectedListener {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()) {
case R.id.drawer_summary:
controller.setFragmentSummary();
break;
case R.id.drawer_income:
controller.setFragmentIncome();
break;
}
return false;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable("controller", controller);
super.onSaveInstanceState(outState);
Log.v(TAG, "onSaveInstanceState, saving the controller");
}
}
My controller class:
public class Controller implements Serializable {
private final String TAG = "Controller: ";
/********************** Fragments ***********************/
private Fragment_Income fragment_income;
private Fragment_Summary fragment_summary;
/********************************************************/
/********************** Activities **********************/
private LoggedInActivity logged_in_activity;
/********************************************************/
public Controller(LoggedInActivity logged_in_activity) {
this.logged_in_activity = logged_in_activity;
initLoggedInFragments();
setFragmentSummary();
}
}
/* Initializes fragments that are connected to LoggedInActivity */
private void initLoggedInFragments() {
fragment_income = new Fragment_Income();
fragment_income.setController(this);
fragment_summary = new Fragment_Summary();
fragment_summary.setController(this);
}
/* use to replace current fragment with the given one */
private void replaceFragmentWith(Fragment fragment) {
logged_in_activity.setFragment(fragment);
}
/***********************************************************
* METHODS REGARDING FRAGMENT INCOME *
**********************************************************/
public void setFragmentIncome() {
replaceFragmentWith(fragment_income);
}
/* Summary fragment is started at first */
public void setFragmentSummary() {
replaceFragmentWith(fragment_summary);
}
}
Fragment_Income:
public class Fragment_Income extends Fragment implements Serializable{
private final String TAG = "Fragment_Income: ";
private Controller controller;
private FloatingActionButton fab_income;
private ListView lv_income;
private ArrayList<LvData> incomeData;
private LvAdapterIncome lvAdapterIncome;
public Fragment_Income() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v(TAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_income, container, false); // Inflate the layout for this fragment
if(savedInstanceState != null) {
this.controller = (Controller) savedInstanceState.getSerializable("controller");
}
initComponents(view);
initListener();
setupListView();
return view;
}
private void initComponents(View view) {
fab_income = (FloatingActionButton) view.findViewById(R.id.fab_income);
lv_income = (ListView) view.findViewById(R.id.lv_income);
}
private void initListener() {
ButtonListener buttonListener = new ButtonListener();
fab_income.setOnClickListener(buttonListener);
}
private void setupListView() {
if (incomeData == null) { // checks if incomeData have been initalized before, if so do not change array to defualt
incomeData = new ArrayList<>();
lvAdapterIncome = new LvAdapterIncome(getContext(), incomeData);
}
lv_income.setAdapter(lvAdapterIncome);
}
public void setController(Controller controller) {
this.controller = controller;
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.v(TAG, "onSaveInstanceState, saving the controller");
outState.putSerializable("controller", this.controller);
super.onSaveInstanceState(outState);
}
}
Fragment_Summary:
public class Fragment_Summary extends Fragment implements Serializable {
private static final String TAG = "Fragment_Summary: ";
private Controller controller;
private TextView tv_user;
private TextView tv_total_revenue;
private TextView tv_total_expenditure;
private TextView tv_balance;
private float totalRevenue;
private float totalExpenditure;
private float balance;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_summary, container, false);// Inflate the layout for this fragment
initComponents(view);
setUserName();
if(savedInstanceState == null) {
//DO SOMETHING
}
return view;
}
private void addData() {
totalRevenue = controller.getTotalRevenue();
totalExpenditure = controller.getTotalExpenditure();
balance = totalRevenue - totalExpenditure;
tv_total_revenue.setText(String.valueOf(totalRevenue));
tv_total_expenditure.setText(String.valueOf(totalExpenditure));
tv_balance.setText(String.valueOf(balance));
}
private void initComponents(View view) {
tv_user = (TextView)view.findViewById(R.id.tv_user);
tv_total_revenue = (TextView)view.findViewById(R.id.tv_revenue);
tv_total_expenditure = (TextView)view.findViewById(R.id.tv_sum_exp);
tv_balance = (TextView)view.findViewById(R.id.tv_balance);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("revenue", String.valueOf(balance));
outState.putString("totalExpenditure", String.valueOf(balance));
outState.putString("balance", String.valueOf(balance));
super.onSaveInstanceState(outState);
}
public void setController(Controller controller) {
this.controller = controller;
}
}
I have removed all the header files and some methods from my classes becuase I tought they were not relevant for this problem.
Here is the error log:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1434)
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1452)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:708)
at android.app.BackStackRecord.commit(BackStackRecord.java:672)
at com.example.user.my_app.LoggedInActivity.setFragment(LoggedInActivity.java:85)
at com.example.user.my_app.Controller.replaceFragmentWith(Controller.java:89)
at com.example.user.my_app.Controller.setFragmentIncome(Controller.java:99)
at com.example.user.my_app.LoggedInActivity$MyNavigationItemListener.onNavigationItemSelected(LoggedInActivity.java:127)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:156)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:342)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
This looks like an activity state loss. See this excellent article by Alex Lockwood entitled "Fragment Transactions & Activity State Loss". I refer to it time and again.
To quote the intro to the posting:
The following stack trace and exception message has plagued StackOverflow ever since Honeycomb’s initial release:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
This post will explain why and when this exception is thrown, and will conclude with several suggestions that will help ensure it never crashes your application again.
I would like to get the value of my checkbox that is in my confiFragment and get that value in MainActivity .
The configFragment is related to the confiActivity.
I tried this method but i get a null ; can someone help me please?
This is my fragment:
public class configFragment extends android.support.v4.app.Fragment {
CheckBox check;
configActivity cmt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.config_layout, container, false);
check = (CheckBox) rootView.findViewById(R.id.checkbox1);
TextView text1=(TextView) rootView.findViewById(R.id.text1);
text1.setText("hello ");
cmt=(configActivity) getActivity();
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(check.isChecked()){
Log.d("status","checked");
//check.setChecked(true);
cmt.checking=true;
}else{
Log.d("status","not checked");
//check.setChecked(false);
cmt.checking=false;
}
}
});
//cmt.checking=load();
// check();
return rootView;
}
#Override
public void onPause() {
super.onPause();
save(check.isChecked());
}
#Override
public void onResume() {
super.onResume();
check.setChecked(load());
}
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.commit();
}
public boolean load() {
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", check.isChecked());
}
}
and this is the activity of this fragment:
public class configActivity extends SingleFragmentActivity {
public Boolean checking;
#Override
protected Fragment createFragment()
{
return new configFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configFragment cf=new configFragment();
SharedPreferences sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
checking=sharedPreferences.getBoolean("check", cf.check.isChecked());
}
}
and this is my main activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView hello=(TextView) findViewById(R.id.hello);
Button but1=(Button) findViewById(R.id.button1);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,configActivity.class);
startActivity(i);
}
});
hello.setText("Hello world");
configActivity config=new configActivity();
Log.d("status of checking",config.checking.toString());
if(config.checking=true){
Log.d("checked","true");
}else{
Log.d("not checked","false");
}
}
You using a wrong way to create communication between fragment to activity.
The correct way to communicate between your activity and fragments is using interfaces.
Define an interface in your configFragment and then implement that in your activity.
And do what ever you want.
Refer this
And if you want to pass this is to your main activity set a Result to main activity from your configActivity. Refer this one for starting activity for result
And also go through this link. Ho to use fragment
I have 2 Fragment and I have to send some id to the Fragment. I use this:
public void onItemLongClick(View view, int position) {
FragmentManager fm = getSupportFragmentManager();
actionOption actionOption = new actionOption();
actionOption.show(fm,"fragment_edit_name");
ToDoModule movie = dbList.get(position);
int y= movie.getId();
Bundle args = new Bundle();
args.putInt("exampleInt", y);
actionOption.setArguments(args);
EditOption editOption = new EditOption();
ToDoModule bl = dbList.get(position);
int z= movie.getId();
Bundle zs = new Bundle();
zs.putInt("int", y);
editOption.setArguments(zs);
}
First Fragment is working, but the second is not sent. Cannot send value to EditOption?
How to solve it?
Its very unusual that, you're trying to pass some data to two Fragment at the same time. It would be great if you could write the situation you have there in brief in your question.
Anyway, #PrerakSola came up with a solution for saving the data you want to pass in a SharedPreference and I do think it should work in your case.
You're trying to pass a movie id to actionOption as well as to editOption. You might try to store the id first in a SharedPreference like this.
From your Activity
public void onItemLongClick(View view, int position) {
// ... Your code
// Save the movie id
SharedPreferences pref = getSharedPreferences("MY_APPLICATION", MODE_PRIVATE);
pref.edit().putInt("MOVIE_ID", movie.getId()).commit();
// Do not pass any bundle to the Fragment. Just transact the Fragment here
}
Now from your Fragment's onCreateView fetch the value from preference.
SharedPreferences pref = getActivity().getSharedPreferences("MY_APPLICATION", MODE_PRIVATE);
String movieID = pref.getInt("MOVIE_ID", 0);
Another way you might try to have a public static int variable which might contain the movie id and you can access it from anywhere from your code.
Hope that helps!
Something like this , you can do it
public interface SetData {
public void data(String id);
}
From your activity class or on item click listner
SetData setData;
setData.setDrawerEnabled("anydata");
Infragment , YourFragment extends Fragment implements SetData
hi yesterday i have done same thing and how it work, i'll give you idea.
It already answered but just i want to share my experiance.This way is perfect.
First of all create two interfaces in your activity,
public interface TaskListener1 {
public void onResultAvailable(String result);
}
public interface TaskListener2 {
public void onResultAvailable(String result);
}
Now come to your activity then call like this where you want to send data to fragment.I'm just giving you example.You can make it as you want.
class TestAsyncTask extends AsyncTask<Void, String, Void> {
String response_result;
public TaskListener1 taskListener1 = null;
public TaskListener2 taskListener2 = null;
public TestAsyncTask(TaskListener1 taskListener1, TaskListener2 taskListener2) {
this.taskListener1 = taskListener1;
this.taskListener2 = taskListener2;
}
#Override
protected Void doInBackground(Void... unused) {
response_result = "Test data what you want to send";
return null;
}
#Override
protected void onPostExecute(Void unused) {
taskListener1.onResultAvailable(response_result);
taskListener2.onResultAvailable(response_result);
}
}
Call like this,
new TestAsyncTask(new Fragment1), new Fragment2)).execute();
And how to get data in fragment,
First fragment,
public class Fragment1 extends Fragment implements YourActivity.TaskListener1 {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment1, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onResultAvailable(String result) {
Logs.d("TAG", "Fragment result1:" + result);
}
}
Second fragment,
public class Fragment2 extends Fragment implements YourActivity.TaskListener2 {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment2, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onResultAvailable(String result) {
Logs.d("TAG", "Fragment result2:" + result);
}
}
Thanks hope this will help somebody.
I want to add a custom view (that contains a layout with button and text view) to every Activity I need my custom view name is NetworkErrorView and I have another class that help me observe network status change!
I want to show my custom view on top of other view in every activity that I bulid my NetworkErrorView like this
private NetworkErrorView networkErrorView=new NetworkErrorView(this).build();
And when network stats is change I want to change visibility from Gone to Visible(onChange is called when my network status changed):
#Override
public void onChange(boolean isConnected) {
networkErrorView.networkErorrDialog(isConnected);
}
My onChange() (method work correctly but i cant see my custom view when I change visibility! Can anyone help me??
NetworkErrorView:
public class NetworkErrorView {
private ViewGroup mRootView;
private Activity mActivity;
private LinearLayoutManager mLayoutManager;
private View view;
private Animation translationIn;
private Button btnNetwork;
private LinearLayout networkContainer;
private boolean networkStatus;
public NetworkErrorView(#NonNull Activity activity) {
this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content);
this.mActivity = activity;
this.mLayoutManager = new LinearLayoutManager(mActivity);
}
public NetworkErrorView build(){
view= Assist.inflater.inflate(R.layout.dialog_network_error,mRootView,false);
//View.inflate(mActivity, R.layout.dialog_network_error, mRootView);
btnNetwork=(Button) view.findViewById(R.id.btn_error_network);
btnNetwork.setOnClickListener(onClickListener);
networkContainer=(LinearLayout) view.findViewById(R.id.layout_error_networkcontainer);
translationIn= AnimationUtils.loadAnimation(mActivity,R.anim.anim_wifi_container_in);
mRootView.addView(view, 1);
return this;
}
public void networkErorrDialog(boolean isConnected){
networkStatus=isConnected;
if(isConnected){
view.setVisibility(View.GONE);
}else {
view.setVisibility(View.VISIBLE);
view.bringToFront();
translationIn= AnimationUtils.loadAnimation(mActivity, R.anim.anim_wifi_container_in);
networkContainer.setAnimation(translationIn);
}
}
View.OnClickListener onClickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!networkStatus){
mActivity.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
}
};
}
mActivity:
public class mActivity extends AppCompatActivity implements NetworkObserver {
private NetworkErrorView networkErrorView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
FontManager.instance().setTypeface(getWindow().getDecorView());
addView();
NetworkManager.init(this);
//...
}
private void addView(){
//...
networkErrorView=new NetworkErrorView(this).build();
}
#Override
public void onChange(boolean isConnected) {
networkErrorView.networkErorrDialog(isConnected);
}
}
I think the view is being added, but because you are adding the view in the 1th position it is not being shown so try something like this
public NetworkErrorView build(){
view= Assist.inflater.inflate(R.layout.dialog_network_error,mRootView,false);
//View.inflate(mActivity, R.layout.dialog_network_error, mRootView);
btnNetwork=(Button) view.findViewById(R.id.btn_error_network);
btnNetwork.setOnClickListener(onClickListener);
networkContainer=(LinearLayout) view.findViewById(R.id.layout_error_networkcontainer);
translationIn= AnimationUtils.loadAnimation(mActivity,R.anim.anim_wifi_container_in);
mRootView.addView(view, 0); //Change this form 1 to 0
return this;
}
i wanna pass a string to all fragment(child) from fragment activity (main), may be this picture can explain what exactly what i want to do
https://dl.dropboxusercontent.com/u/57465028/SC20140205-163325.png
so, from above picture...i wanna pass a string from edittext by press a button to all activity in viewpager....how could i do that?
i tried to follow this code https://stackoverflow.com/a/12739968/2003393 but it can't solved my problem..
please help me...i'm stuck
thank in advance.
here is my code from fragment activity (MainActivity)
public class Swipe_Menu extends FragmentActivity {
//String KeyWord;
//private static final String KEYWORD = "keyword";
private ViewPager _mViewPager;
private ViewPagerAdapter _adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.swipe_menu_image);
Button Back = (Button)findViewById(R.id.account);
ImageButton Search = (ImageButton)findViewById(R.id.search);
EditText Keyword = (EditText)findViewById(R.id.keyword);
final String KeyWord = Keyword.getText().toString();
/**
* Back button click event
* */
Back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
setUpView();
setTab();
}
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", KeyWord );
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
and here is my fragment (Child Activity)
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
String KeyWord;
private TextView kata_keyword;
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
KeyWord = value;
}
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/*Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");*/
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
//ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}
You don't have access directly to your fragments that reside in ViewPager so you can't reference them directly.
What I am doing in these cases is send a broadcast message from Activity to Fragments. For this reason register a BroadcatReceiver in the fragment (either in onCreate or onCreateView - your decision)m, set a custom action for that receiver (ex. "my_package.actions.internal.BROADCAST_ACTION"), don't forget to unregister the receiver from complementary method.
When you want to send a message from activity, create an intent with above mentioned action, add the string in intent extra and send the broadcast.
In your receiver's onReceive method (within the fragment), get the String from intent paramter and there you have the string.
Makes sense?
EDIT: To provide some code, below are the changes that I would make for fragment:
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
kata_keyword.setText(value);
}
String KeyWord;
private TextView kata_keyword;
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}
And this code I would have from activity, the parameter is the value from EditText:
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", value);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
You would call this from the click listener that you would set in onCreate:
findViewById(R.id.button_id).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String valueThatYouWantToSend = null; /// just the value
sendValueToFragments(valueThatYouWantToSend);
}
});
// I think this solution will solved your issue
// In Main activity put your code -----------------------------------
public void onPageSelected(int position)
{
System.out.println("nilesh");
PageOneFragment f = new PageOneFragment();
f.getText();
PageTwoFragment ff = new PageTwoFragment();
ff.setText();
}
//in General Class ------------------------------------------------
public class General
{
public static String name="";
}
// first Fragment ---------------------------------------------
public void getText()
{
General.name = edittext.getText().toString();
}
// second Fragment ----------------------------------------------
public void setText()
{
System.out.println("name**" + General.name);
tv.setText(General.name);
}