I will be very grateful for the analysis of these lines of code, because I do not understand the relationship between them. Especially if I
I will change tags to 2 different tags, nothing changes in the application. In addition, if the condition if is removed, there are also no changes. In the comments I have a brief translation, I am still unable to understand these three lines.
Fragment fr = manager.findFragmentByTag("AddCity");
What role does this condition fulfill?
if (fr != null) {// if ???
manager.beginTransaction().remove(fr).commit();
}
And:
fr2.show(manager, "AddCity");
This is the whole code snippet
/*
I create a variable manager, and then I get a FragmentManager and assign it to the variable manager,
thanks to the variable manager, I can run actions on fragments
*/
FragmentManager manager = getSupportFragmentManager();
Fragment fr = manager.findFragmentByTag("AddCity");//I created fr variable and ???
Fragment1 fr1 = (Fragment1)
manager.findFragmentById(R.id.list); // I created fr1 variable and assigned fragment list to the variable fr1
if (view.equals(b1)) {
if (fr != null) {// if ???
manager.beginTransaction().remove(fr).commit();//Creates a new transaction to change fragments at runtime, removes an existing fragment, plans to commit the transaction.
}
Fragment2 fr2 = new Fragment2();//Created object Fragment2
fr2.show(manager, "AddCity");//Display the dialog box by adding the fragment to the given FragmentManager.
}
EDIT:
This is my MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button b1, b2;
static int itemSelected;
static boolean isSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.button1);
b2 = findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
FragmentManager manager = getSupportFragmentManager();//
Fragment fr = manager.findFragmentByTag("addCity");
Fragment1 fr1 = (Fragment1)
getSupportFragmentManager().findFragmentById(R.id.list);
if (view.equals(b1)) {
if (fr != null) {
manager.beginTransaction().remove(fr).commit();
}
Fragment2 fr2 = new Fragment2();
fr2.show(manager, "");
}
if (view.equals(b2)) {
if (!fr1.cities.isEmpty()) {
if (isSelected) {
fr1.cities.remove(itemSelected);
fr1.adapter.notifyDataSetChanged();
itemSelected = 0;
isSelected = false;
fr1.getListView()
.setSelector(android.R.color.transparent);
} else {
Toast.makeText(this, "Select city to be deleted",
Toast.LENGTH_LONG).show();
}
}
}
}
}
Fragment1:
public class Fragment1 extends ListFragment {
ArrayList<String> cities = new ArrayList<>();
ArrayAdapter<String> adapter;
String name;
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment1,
viewGroup, false);
adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, cities);
setListAdapter(adapter);
return view;
}
public void onListItemClick(ListView listView, View view,
int position, long id) {
MainActivity.itemSelected = position;
MainActivity.isSelected = true;
getListView().setSelector(android.R.color.holo_blue_dark);
}
}
Fragment2:
public class Fragment2 extends DialogFragment {
EditText et;
public Fragment2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment2, viewGroup, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
et = view.findViewById(R.id.editText);
Button b = view.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String country = et.getText().toString();
Fragment1 fr1 = (Fragment1)
getFragmentManager().findFragmentById(R.id.list);
if (!country.equals("")) {
fr1.cities.add(country);
fr1.adapter.notifyDataSetChanged();
}
getActivity().getSupportFragmentManager().beginTransaction()
.remove(Fragment2.this).commit();
}
});
}
}
You are adding another fragment in the same name. Can you try changing the name to something else and try?
Like
fr2.show(manager, "Add District");
so that you can find the difference.
Adding a fragment
Fragment fr2 = new Fragment();
FragmentManager manger = getSupportFragmentManager();
FragmentTransaction ft = manger.beginTransaction();
ft.add(R.id.placeHolder, fr2,tag);
ft.commitAllowingStateLoss();
if(fr2.isAdded()){
fr2.show(manager, "");
}
Before calling show, you have to add the fragment.
Related
I open a dialog fragment from A fragment, and when the dialog fragment is closed,
I want to switch from A fragment to B fragment at the same time.
But I keep getting Fragment already added error.
I am using show() instead of replace() to change the screen.
Fragment already added error was easily solved on the web, but
I don't work out weird.
Probably there is a problem with my code, please let me know where the problem is.
MainActivity.java
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNav;
FragmentManager fm;
FragmentTransaction transaction;
Fragment curFrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fm = getSupportFragmentManager();
transaction = fm.beginTransaction();
curFrag = fm.getPrimaryNavigationFragment();
String tag = String.valueOf(item.getItemId());
int id = item.getItemId();
if(curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if(fragment == null) {
if(id == R.id.list)
fragment = new WorkoutListFragment();
transaction.add(R.id.content_layout, fragment, tag);
}
else {
transaction.show(fragment);
}
transaction.setPrimaryNavigationFragment(fragment);
transaction.setReorderingAllowed(true);
transaction.commitNow();
return true;
}
});
}
// Method for screen switching
public void onFragmentChanged() {
// transaction = fm.beginTransaction();
String tag = "WriteRoutine";
curFrag = fm.getPrimaryNavigationFragment();
if (curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if (fragment == null) {
fragment = new WriteRoutineFragment();
fragment.setArguments(curFrag.getArguments());
transaction.add(R.id.content_layout, fragment, tag);
} else {
transaction.show(fragment);
}
transaction.setReorderingAllowed(true);
transaction.commit();
}
}
WorkoutListFragment.java (A Fragment)
public class WorkoutListFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getParentFragmentManager().setFragmentResultListener("result", this, new FragmentResultListener(){
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle result) {
if(result != null)
WorkoutListFragment.this.setArguments(result);
titleData = result.getStringArrayList("title");
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.activity_workout_list, container, false);
initViews(rootView);
((AppCompatActivity) getActivity()).setSupportActionBar((toolbar));
return rootView;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
menu.clear();
inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.record_item_add, menu);
}
#Override // open dialog
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
BodyPartDialogFragment dialog = new BodyPartDialogFragment();
dialog.show(getActivity().getSupportFragmentManager(), "BodyPartDialog");
return true;
}
}
DialogFragment.java
public class BodyPartDialogFragment extends DialogFragment {
Button startBtn;
ArrayList<String> bodypart_strData;
int selectedNum;
final static String TAG = "DialogFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_body_part_dialog, null);
startBtn = view.findViewById(R.id.check);
// A D D
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedNum == 0){
Toast.makeText(getContext(), "Plaese select", Toast.LENGTH_SHORT).show();
}
else {
MainActivity activity = (MainActivity) getActivity();
Bundle result = new Bundle();
result.putStringArrayList("title", bodypart_strData);
getParentFragmentManager().setFragmentResult("result", result);
activity.onFragmentChanged();
dismiss();
}
}
});
return view;
}
Upon testing your code, you'll just need to reinstantiate the transaction object before adding/replacing your fragment.
So, you need to add below in onFragmentChanged():
transaction = getSupportFragmentManager().beginTransaction();
And here it is:
// Method for screen switching
public void onFragmentChanged() {
String tag = "WriteRoutine";
transaction = getSupportFragmentManager().beginTransaction(); // <<< THE CHANGE IS HERE
curFrag = fm.getPrimaryNavigationFragment();
if (curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if (fragment == null) {
fragment = new WriteRoutineFragment();
fragment.setArguments(curFrag.getArguments());
transaction.add(R.id.content_layout, fragment, tag);
} else {
transaction.show(fragment);
}
transaction.setReorderingAllowed(true);
transaction.commit();
}
I have main activity which contains fragments. One of the fragment is calling dialogFragment for new item entry. This new item is specified by Serializable class.
Just to be more specific:
item.java
public class Item implements Serializable {
private String mTitle;
private String mDescription;
private Boolean mTrue;
//getters and setters
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
public Boolean isTrue() {
return mTrue;
}
public void setTrue(Boolean mTrue) {
this.mTrue = mTrue;
}
}
DialogNewItem
public class DialogNewItem extends DialogFragment {
//filters state holder
Boolean isTrue = false;
//filters state end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.new_item, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription)
//filter icons
final ImageView ivIsTrue = (ImageView) dialogView.findViewById(R.id.filterTrue);
//filter icons end
//onClickListener for filter icons
ivIsTrue.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (isTrue == false) {
ivIsTrue.setBackgroundResource(R.drawable.border_white);
ivIsTrue.setImageResource(R.drawable.true_white);
isTrue = true;
} else {
ivIsTrue.setBackgroundResource(R.drawable.border_green);
ivIsTrue.setImageResource(R.drawable.true_green);
isTrue = false;
}
}
});
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView);
//cancel button
btnCancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dismiss();
}
});
//give button
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
dismiss();
}
});
return builder.create();
}
}
Now, I want to pass newItem from DialogNewItem (btnOK) to a listView Fragment. In other words I want to make a listView Fragment which will contain all the new items created in DialogNewItem.
I was trying different methods (set/getFragment, ArrayList, different interfaces, etc) but some how non of it works. I have no problem with passing newItem to listView in an activity:
//get the reference to dashboard
Dashboard callingActivity = (Dashboard) getActivity();
//pass new item back to dashboard
callingActivity.createNewItem(newItem);
and then dashboard activity:
public class Dashboard extends AppCompatActivity {
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
mItemAdapter = new ItemAdapter();
ListView listItem = (ListView) findViewById(R.id.listView);
listItem.setAdapter(mItemAdapter);
}
//handle clicks on listView
listItem.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> adapter, View view, int whichItem, long id ){
//creating temporary item which is reference to the clicked item
Item tempItem = mItemAdapter.getItem(whichItem);
//new dialog window
DialogShowItem dialog = new DialogShowItem();
//send reference to the item to be shown
dialog.sendItemSelected(tempItem);
//show the dialog window with the item
dialog.show(getFragmentManager(),"");
}
});
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup){
//has been inflated already
if (view==null){
//creating layout inflater
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//instantiate view by inflating inflater (listItem layout)
view = inflater.inflate(R.layout.listitem, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
//grabbing the refrence to all variables
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide not relevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
//category with different image src
return view;
}
and everything works perfectly, but when I want to do the same with Fragment instead of Activity, somehow I cannot make it work.
I would appreciate any help. Thanx
Fragment (with listview):
public class ListItems extends ListFragment {
private ItemAdapter mItemAdapter;
public void createNewItem(Item i) {
mItemAdapter.addItem(i);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstatceState) {
View view = inflater.inflate(R.layout.list_items, container, false);
//Item adapter
mItemAdapter = new ItemAdapter();
final ListView listItems = (ListView) view.findViewById(R.id.listView);
listItems.setAdapter(mItemAdapter);
//floating give button
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogNewItem dialog = new DialogNewItem();
dialog.show(getFragmentManager(), "");
}
});
//handle clicks on itemList
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {
Item tempItem = mItemAdapter.getItem(whichItem);
DialogShowItem dialog = new DialogShowItem();
dialog.sendItemSelected(tempItem);
dialog.show(getFragmentManager(), "");
}
});
return view;
}
#Override
protected void onPause() {
super.onPause();
mItemAdapter.saveItems();
}
public class ItemAdapter extends BaseAdapter {
List<Item> itemList = new ArrayList<Item>();
private JSONSerializer mSerializer;
public ItemAdapter() {
mSerializer = new JSONSerializer("myProject.json", getActivity().getApplicationContext());
try {
itemList = mSerializer.load();
} catch (Exception e) {
itemList = new ArrayList<Item>();
Log.e("Error loading items: ", "", e);
}
}
public void saveItems() {
try {
mSerializer.save(itemList);
} catch (Exception e) {
Log.e("Error saving items: ", "", e);
}
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Item getItem(int whichItem) {
return itemList.get(whichItem);
}
#Override
public long getItemId(int whichItem) {
return whichItem;
}
public void addItem(Item n) {
itemList.add(n);
notifyDataSetChanged();
}
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup) {
if (view==null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_items, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide irrelevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
return view;
}
}
}
It's a drawer activity so I'm showing it after drawer item click:
private void switchFragment(int position) {
Fragment fragment = null;
String fragmentID = "";
switch (position) {
case 0:
fragmentID = "LISTITEMS";
fragment = new ListItems();
break;
case 1:
fragmentID = "PROFILE";
fragment = new Profile();
break;
default:
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragmentHolder, fragment, fragmentID).commit();
//close the drawer
mDrawerLayout.closeDrawer(mNavDrawerList);
}
You can make a public method in ListItems fragment class in which you receive an Item class object and add it in adapter. And then inside your DialogNewItem Fragment, On OK Button click, you can search the ListItems using SupportFragmentManager by using its tag and call the public method you wrote.
The following code might help you.
DialogNewItem class
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
FragmentManager manager = getActivity().getSupportFragmentManager();
ListItems fragment = (ListItems)manager.findFragmentByTag("LISTITEMS");
if(fragment != null){
fragment.createNewItem(newItem);
}
dismiss();
}
});
In your ListItems fragment the following code will depict an ItemAdapter as the data member of the ListViewFragment class and below that is the method you can call to add the item in the adapter.
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
I want to get an ArrayList from one Fragment to another, I use the Intentmethod, like this:
Fragment where I want to get it from
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putStringArrayListExtra("server_name_list", server_name_list);
If I debug this, I can see the new entry I did. But in the Fragment where I use getIntent().getStringArrayListExtra there is no new entry.
What did I wrong?
Here is the code from the Fragment where I use the method:
/* Server Name Spinner */
ArrayList<String> server_name_list = getIntent().getStringArrayListExtra("server_name_list");
if (server_name_list != null) {
spinner = (Spinner) view.findViewById(R.id.server_spinner);
;
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = parent.getItemAtPosition(pos).toString();
myWebView.loadUrl(selected);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Edit: Whole code
public class MainActivity extends AppCompatActivity implements AddServerFragment.Callback {
static WebView myWebView;
Fragment AddServerFragment, WebViewFragment;
ArrayList<String> server_name_list;
#Override
public ArrayList<String> getArrayListFromActivity() {
WebViewFragment frag = (WebViewFragment) getSupportFragmentManager().findFragmentByTag("AddServerFragment");
if (frag != null) {
server_name_list = frag.getArrayListFromWebViewFragment();
}
return server_name_list;
}
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.webview:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new WebViewFragment() {
})
.commit();
return true;
case R.id.add_server:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new AddServerFragment() {
})
.commit();
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.container) != null) {
if (savedInstanceState != null) {
return;
}
AddServerFragment = new Fragment();
WebViewFragment = new Fragment();
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new WebViewFragment() {
})
.commit();
}
/*WebView Fragment*/
public class WebViewFragment extends Fragment {
String selected;
Spinner spinner;
public WebViewFragment(){
}
private Callback callback;
public interface Callback {
public ArrayList<String> getArrayListFromActivity();
}
#Override
public void onAttach(Activity activity) {
callback = (Callback) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
/* WebView */
myWebView = (WebView) view.findViewById(R.id.webView);
myWebView.setWebViewClient(new WebC());
WebSettings webSettings = myWebView.getSettings();
/* JavaScript Enable */
webSettings.setJavaScriptEnabled(true);
/* Server Name Spinner */
ArrayList<String> server_name_list = callback.getArrayListFromActivity();
if (server_name_list != null) {
spinner = (Spinner) view.findViewById(R.id.server_spinner);
;
ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_spinner_item, server_name_list);
server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(server_adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = parent.getItemAtPosition(pos).toString();
myWebView.loadUrl(selected);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
return view;
}
}
/*Add Server Fragment*/
public class AddServerFragment extends Fragment
implements View.OnClickListener {
#Override
public void onClick(View view) {
}
public AddServerFragment(){
}
Button btn_back, btn_add;
EditText server_ip, server_name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_ip, container, false);
server_ip = (EditText) view.findViewById(R.id.edit_server_address);
server_name = (EditText) view.findViewById(R.id.edit_server_name);
btn_back = (Button) view.findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new WebViewFragment() {
})
.commit();
}
});
btn_add = (Button) view.findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String new_server_ip = null, new_server_name = null;
ArrayList<String> server_name_list = new ArrayList<>();
ArrayList<String> server_ip_list = new ArrayList<>();
new_server_ip = server_ip.getText().toString();
server_ip_list.add(new_server_ip);
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
}
});
return view;
}
}
/* WebView Client */
public class WebC extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
}
You can store your ArrayList as a member variable of your container activity :
private ArrayList<String> server_name_list;
Add a getter:
public ArrayList<String> getArrayList() {
return server_name_list;
}
And in your fragments, you access it this way: (supposing that the container activity's name is MainActivity)
ArrayList<String> arraylist = ((MainActivity)getActivity()).getArrayList();
JDev's answer is correct in so far as it will give you the result you want with the smallest amount of code. It is also, conceptually, the easiest method to understand. However, the technique recommended by Android Developers for a Fragment to communicate with its hosting Activity is via an interface.
It is worth learning this technique IMO, even if you are unfamiliar with interfaces in Java and Android. This is because interfaces are used in all but the most basic of projects, and they underpin many recommended design patterns, so you can be sure they will turn up sooner or later :)
Here is how you would solve your problem with an interface:
public class MyFragment extends Fragment {
private Callback callback;
public interface Callback {
public ArrayList<String> getArrayListFromActivity();
}
#Override
public void onAttach(Activity activity) {
callback = (Callback) activity;
//NB: The above will throw ClassCastException if your Activity
//Does not implement MyFragment.Callback
}
//Later in your code, whenever you want to grab the ArrayList<String> from your Activity:
ArrayList<String> arrList = callback.getArrayListFromActivity();
Inside MainActivity:
public class MainActivity extends AppCompatActivity implements MyFragment.Callback {
ArrayList<String> arrayList;
#Override
public ArrayList<String> getArrayListFromActivity() {
//If the ArrayList is in your Activity, then use:
return arrayList;
//If the ArrayList is in another Fragment, then use:
FragmentTwo frag = (FragmentTwo) getSupportFragmentManager().findFragmentByTag("tag_of_fragment_two");
if (frag != null) {
arrayList = frag.getArrayListFromFragmentTwo();
return arrayList;
}
}
}
ArrayList<String> server_name_list;//declare variable
... void onCreate(...)
{
.
.
.
server_name_list = getIntent().getStringArrayListExtra("server_name_list");//assign value
}
try this.if doesn't work try
intent.putExtra("server_name_list", server_name_list);
instead of
intent.putStringArrayListExtra("server_name_list", server_name_list);
you can simply pass any parameter through static instance of that fragment.
intent is normally used to transfer data among activities not fragments
DestinationFragment Frag = DestinationFragment.getInstance(yourArrayList);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (shouldAddToBackStack)
ft.addToBackStack(tag);
else {
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
ft.replace(R.id.container, Frag, tag)
.commit();
getSupportFragmentManager().executePendingTransactions();
in your DestinationFragment
public static DestinationFragment getInstance(ArrayList yourArrayList){
DestinationFragment fragment=new DestinationFragment();
Bundle args = new Bundle();
args.putString(args, yourArrayList);
fragment.setArguments(args);
return fragment;
}
I have a problem with comuunicating between fragments that are chnged dynamicaly, i mannaged to use the interface system to cimmunicate if the fragments are all viewble but when i am viewing them sepretly i can't use a their actions since they dont have a tag yet, any thoughts?
main activty
public class MainActivity extends FragmentActivity implements OnClickListener, Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (isSingleFragment()) {
Button btn_color = (Button) findViewById(R.id.button_color);
Button btn_text = (Button) findViewById(R.id.button_text);
Button btn_list = (Button) findViewById(R.id.button_list);
btn_color.setOnClickListener(this);
btn_list.setOnClickListener(this);
btn_text.setOnClickListener(this);
singleFragActions();
} else {
doubleFragActions();
}
// some more stuff happens
#Override
public void apply(String data) {
Log.d("data", data+"");
FragmentManager fm = getSupportFragmentManager();
Frag_list frag_list = (Frag_list) fm.findFragmentByTag("list");
//i cannot use id because the fragment in
//MainActivity are in a layout and are enterd dynamicaly
frag_list.addItem(data);
}
three fragments here, when on small screen, on is shown and three button on the top change them arrounf, if on tablet, all three are displyed, this is the interface
public interface Communicator {
public void apply(String data);
}
frag_text (first fragment)
public class Frag_text extends Fragment implements OnClickListener{
Communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// stuff
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
comm = (Communicator) getActivity();
}
#Override
public void onClick(View v) {
EditText input = (EditText) getView().findViewById(R.id.frag_text_edit);
TextView output = (TextView) getView().findViewById(R.id.frag_text_show);
String text_get = input.getText().toString();
output.setText("hello "+text_get+" how are you today?");
comm.apply(text_get);
}
}
frag_list (other fragment)
public class Frag_list extends Fragment{
ArrayList<String> list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_list, container, false);
list = new ArrayList<String>();
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list);
ListView lv = (ListView) view.findViewById(R.id.list_frag);
lv.setAdapter(adapter);
return view;
}
public void addItem(String data){
list.add(data);
}
}
how to i access the other fragment if it doesnt have a tag yet?
If you happen to know what fragment you will be calling then FragmentActivity could act as a mediator in this case, as it is a mere "host". You already have this Communicator interface. Have it communicate to a given fragment:
public interface Communicator {
public void apply(String data, String tag);
}
And the override:
#Override
public void apply(String data, String tag) {
FragmentManager fm = getSupportFragmentManager();
Frag_list frag_list = (Frag_list) fm.findFragmentByTag(tag);
//Fallback plan in case the fragment has not been created.
if(frag_list == null) {
frag_list = new Frag_list();
//Include the fragment for future reference.
//This fragment has no view
fm.beginTransaction().add(frag_list, tag);
}
frag_list.addItem(data);
}
And modify the fragment to always have the list available:
public class Frag_list extends Fragment{
ArrayList<String> list = new ArrayList<String>();
//...
public void addItem(String data){
//Add check to avoid problems
if(list != null) {
list.add(data);
}
}
}
I've make it more simple and updated it based on the answers in my previous post: Adding Assigned Values in Spinner NullPointerException
I have a MainAcitivty that uses a ViewPager. I have 2 Fragments in my MainActivity (FragA and FragB)
In my FragA I have a spinner. While in FragB, I have a TextView and a Button.
Now what am I trying to do is, when I select "Hello" in my spinner, my int a will have a value of 5. And when I click the Button, 5 will display in the TextView.
Here's my code:
FragA
public class FragA extends Fragment {
Spinner spinner1;
String s1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fraga, container, false);
spinner1 = (Spinner) view.findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter_a = ArrayAdapter.createFromResource(getActivity(), R.array.spinner1,android.R.layout.simple_spinner_item );
spinner1.setAdapter(adapter_a);
s1 = spinner1.getSelectedItem().toString();
return view;
}
public int getInt() {
int a = 0;
if(s1.equals("Hello")) {
a = 5;
}
return a;
}
}
MainActivity
public class MainActivity extends FragmentActivity {
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if (i == 0)
{
fragment = new FragA();
}
if (i == 1)
{
fragment = new FragB();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
public String get() {
FragA FragA = new FragA();
return Integer.toString(FragA.getInt());
}
}
FragB
public class FragB extends Fragment{
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragb, container, false);
textView = (TextView) view.findViewById(R.id.textview);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(Click);
return view;
}
OnClickListener Click = new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(((MainActivity)getActivity()).get());
}
};
}
By the way, I have no problem passing the value of a from FragA to FragB when this is my code:
public int getInt() {
int a = 5;
return a;
}
But, it doesn't involve my spinner and that's not I want to do.
Here is a simple way to communicate between fragments.
In MainActivity, keep static instances of the fragments.
public static FragA fragmentA;
public static FragB fragmentB;
Now if you want to access FragB from FragA, write something similar:
((MainActivity) getActivity()).fragmentB.setSomething();
And Here is a better/proper way to communicate between fragments:
http://developer.android.com/training/basics/fragments/communicating.html