Passing data from Fragments to Fragments error - java

I use a Bundle to pass data between Fragments. However, I ran into some problems. My Bundle is not working, I do not know why. Because I do everything as I did before.
Here is my Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jegyek);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_lista,
new Tantargylista()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_tantargylista:
selectedFragment = new ObjectList();
break;
case R.id.nav_dolgozatlista:
selectedFragment = new ExamList();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_lista,
selectedFragment).commit();
return true;
}
};
}
My first Fragment:
View v;
DB mydb;
ListView listView;
String teszt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_objectlist, container, false);
listView = (ListView)v.findViewById(R.id.Jegyekview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Empty", Toast.LENGTH_SHORT).show();
} else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
bundle.putString("test", teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
FragTan.commit();
}
}
});
}
return v;
}
There is a second Fragment which has a Button. If the Button is pressed, then the third Fragment is open.
Button button = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan2 = getFragmentManager().beginTransaction();
FragTan2.replace(R.id.fragment_container_lista,jegyekAllando);
FragTan2.commit();
}
});
My third Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = getArguments();
String jegyAtlagSt = bundle.getString("test");
//Here crash the program. :/
return rootView;
}

You have not passed anything from your second Fragment while opening your third Fragment. Hence you need to do something like the following.
Button button = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
// Get a bundle
Bundle bundle = new Bundle();
bundle.putString("test", teszt);
// Set as argument
jegyekAllando.setArguments(bundle);
// Begin the transaction
FragmentTransaction FragTan2 = getFragmentManager().beginTransaction();
FragTan2.replace(R.id.fragment_container_lista,jegyekAllando);
FragTan2.commit();
}
});

I think the problem is your second fragment is not passing the bundle from the first fragment to the third fragment in this code
Button button = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan2 = getFragmentManager().beginTransaction();
FragTan2.replace(R.id.fragment_container_lista,jegyekAllando);
FragTan2.commit();
}
});

Related

android shared element transition with fragments doesn't show exit animation

I have a main activity that handles the static elements, attached to the main activity there is a fragment, this fragment has a tablelayout with a viewpager2, each page shows a recycler view.
The shared element transition works well from FRAGMENT A(Tab_1) to FRAGMENT B(ElementDetails), but when I press the back button, the return shared element transition doesn't work.
TAb_1(Fragment A):
public class tab1_anime extends Fragment {
private RecyclerView recycler_view;
public static AFSGAdapter adapter;
private ArrayList<AddElement> a_list = new ArrayList<>();
private Context context;
public tab1_anime(){ };
#Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState) {
View view = inflater.inflate(R.layout.fragment_tab1_anime, container, false);
recycler_view = view.findViewById(R.id.recycler_view);
recycler_view.setHasFixedSize(true);
context = getActivity();
LinearLayoutManager layoutManager_anime_crucial = new GridLayoutManager(getContext(), 3, GridLayoutManager.VERTICAL, false);
recycler_view.setLayoutManager(layoutManager_anime_crucial);
recycler_view.setItemAnimator(new DefaultItemAnimator());
int spanCount = 3; // 3 columns
int spacing = 10; // 10 for my phone, 35 for the emulator
boolean includeEdge = true;
recycler_view.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
adapter = new AFSGAdapter(a_list, getContext(), this);
adapter.setDataSet(a_list);
recycler_view.setAdapter(adapter);
recycler_view.scheduleLayoutAnimation();
adapter.notifyDataSetChanged();
return view;
}
public void openShowElementFragment(int position, View view) {
AddElement element = a_list.get(position);
ShowElementFragment showElementFragment = new ShowElementFragment();
Bundle bundle = new Bundle();
bundle.putString("transitionName", "transition" + position);
bundle.putSerializable("element", element);
showElementFragment.setArguments(bundle);
((MainActivity) context).showFragmentWithTransition(this, showElementFragment, "showElementFragment", view, "transition" + position);
}
}
ShoeElementDetails(Fragment B):
public class ShowElementFragment extends Fragment {
private AddElement elemento;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_show_element, parent, false);
//showelement_background_image.setTransitionName("example_transition");
Bundle b = getArguments();
if (b != null) {
String transitionName = b.getString("transitionName");
elemento = (AddElement) b.getSerializable("element");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
showelement_image.setTransitionName(transitionName);
}
}
//postponeEnterTransition();
Glide.with(this)
.load(elemento.image_url)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(false)
.apply(RequestOptions.bitmapTransform(new BlurTransformation(10, 3)))
.into(showelement_background_image);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().getSharedElementEnterTransition().setDuration(800);//.setInterpolator(new AccelerateInterpolator());
getActivity().getWindow().getSharedElementReturnTransition().setDuration(850);//.setInterpolator(new DecelerateInterpolator());
}
showelement_backarrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentHolder, new MainFragment())
.commit();
//startActivity(new Intent(ShowElementActivity.this, AnimeActivity.class));
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
postponeEnterTransition();
OneShotPreDrawListener.add(view, this::startPostponedEnterTransition);
super.onViewCreated(view, savedInstanceState);
}
}
Inside the adapter I handle the click of the element to start the transition:
inside adapter:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public void onClick(View v) {
fragment.openShowElementFragment(holder.getAdapterPosition(), v.findViewById(R.id.main_image));
}
});
the openShowElementFragment called is inside main activity:
public void showFragmentWithTransition(Fragment current, Fragment newFragment, String tag, View sharedView, String sharedElementName) {
FragmentManager fragmentManager = getSupportFragmentManager();
// check if the fragment is in back stack
boolean fragmentPopped = fragmentManager.popBackStackImmediate(tag, 0);
if (fragmentPopped) {
// fragment is pop from backStack
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
current.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
current.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setEnterTransition(TransitionInflater.from(this).inflateTransition(android.R.transition.no_transition));
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentHolder, newFragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.addSharedElement(sharedView, sharedElementName);
fragmentTransaction.commit();
}
}
It's my first time approaching with fragments.

How do I fix Fragment already added in my code?

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();
}

Fragments - tag, condition and show

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.

Passing spinner value from activity to fragment

I have a custom spinner with an ArrayList defined in an activity. On selected item a new fragment is created. Can I pass the value of which fragment was created ("Single Massage" or "Couples Massage") to another fragment within the same activity and then from that fragment pass it to another activity and update its textview? This might not be the best approach, but I am a beginner, so I really don't know that much. Here is my code.
Spinner:
public class MassageActivity extends AppCompatActivity {
private Spinner mSpinner;
private Toolbar mToolbar;
private FragmentManager mFragmentManager;
private FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_massage);
mToolbar = (Toolbar) findViewById(R.id.toolbar_massage);
setSupportActionBar(mToolbar);
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}
if (ab != null) {
ab.setDisplayShowTitleEnabled(false);
}
customSpinner();
mFragmentManager = getSupportFragmentManager();
}private void customSpinner() {
final ArrayList<String> massageType = new ArrayList<>();
massageType.add("Single Massage");
massageType.add("Couples Massage");
massageType.add("Pamper Party");
mSpinner = (Spinner) findViewById(R.id.spinner);
CustomSpinnerAdapter spinnerAdapter = new CustomSpinnerAdapter(getApplicationContext(), massageType);
mSpinner.setAdapter(spinnerAdapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getItemAtPosition(position).toString()
.equals("Pamper Party")) {
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment_container_massage,
new PamperPartyFragment()).commit();
}
if (parent.getItemAtPosition(position).toString()
.equals("Single Massage")) {
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment_container_massage,
new SingleMassageFragment()).commit();
}
if (parent.getItemAtPosition(position).toString()
.equals("Couples Massage")){
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment_container_massage,
new CouplesMassageFragment()).commit();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}}
EDIT:
I followed the and done this:
String spinnerValue = mSpinner.getSelectedItem().toString();
Intent i = new Intent(this, SingleMassageFragment.class);
i.putExtra("spinnerValue", spinnerValue);
setIntent(i);
And then in my fragment:
MassageActivity activity = (MassageActivity) getActivity();
Intent f = activity.getIntent();
String spinnerValue = f.getStringExtra("spinnerValue");
Utils.doToast(getContext(), spinnerValue);
But whichever fragment I selected, I always get the same toast "Single Massage". Why is that? For any case here's my adapter:
public class CustomSpinnerAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mMassageType;
private LayoutInflater mInflater;
private TextView tvSpinner;
public CustomSpinnerAdapter(Context context, ArrayList<String> massageType) {
mContext = context;
mMassageType = massageType;
mInflater = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return mMassageType.size();
}
#Override
public Object getItem(int position) {
return mMassageType.get(position);
}
#Override
public long getItemId(int position) {
return (long) position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(R.layout.spinner_layout, null);
tvSpinner = (TextView) convertView.findViewById(R.id.tvSpinner);
tvSpinner.setText(mMassageType.get(position));
return convertView;
}
}
To Pass Data
PamperPartyFragment mPamperPartyFragment = new PamperPartyFragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
mPamperPartyFragment.setArguments(bundle);
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment_container_massage,
mPamperPartyFragment ).commit();
For Getting data in fragment
Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue);
try This in your spinner setOnItemSelectedListener to send data
Bundle bundle = new Bundle();
bundle.putString("spinnerValue",parent.getItemAtPosition(position).toString());
mPamperPartyFragment.setArguments(bundle);
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.fragment_container_massage,
mPamperPartyFragment ).commit();
to read data in your fragment add this in your onCreate
Bundle bundle = getArguments();
String selectedVAlue = bundle.getString("spinnerValue");
in activity :
Intent i = new Intent (this, fragmentname.class);
i.putInt(key, value);
setIntent(i);
in fragment :
ActivityName activity = (ActivityName) getActivity();
Intent f= activity.getIntent();
int yrid = f.getIntExtra(key);

Add Item to ListView

I'm trying to add items at runtime to ListView placed on Tab.
But when I do so, I get an error. There are 3 tabs and I'm not using ListFragments, because I have different content in all tabs
my code below
SwipeTabFragment.java
public class SwipeTabFragment extends Fragment {
private String tab;
private int color;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
tab = bundle.getString("tab");
color = bundle.getInt("color");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bookshelf, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(tab);
view.setBackgroundResource(color);
return view;
}
}
TabPagerAdapter.java
public class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
Bundle bundle = new Bundle();
String tab = "";
int colorResId = 0;
SwipeTabFragment swipeTabFragment = new SwipeTabFragment();
switch (index) {
case 0:
tab = "BookShelf";
bundle.putString("tab",tab);
swipeTabFragment.setArguments(bundle);
return swipeTabFragment;
// break;
case 1:
tab = "Now Listening";
colorResId = R.color.color2;
BookFragment bookFragment = new BookFragment();
return bookFragment;
//break;
case 2:
tab = "Library";
colorResId = R.color.color3;
TabLibrary tabLibrary = new TabLibrary();
return tabLibrary;
break;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
TabLibrary.java
public class TabLibrary extends Fragment {
final String LOG_TAG = "myLogs";
ListView lvLibList;
ImageButton btAddItem;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.library, parent, false);
ListView lvLibList = (ListView)v.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)v.findViewById(R.id.btAddItem);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText)v.findViewById(R.id.eAddItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return v;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
#Gurusharan S is right, the problem is about the names of your variables. To avoid confusions I'd suggest to change your code to this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.library, parent, false); //Change the name from v to view
ListView lvLibList = (ListView)view.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)view.findViewById(R.id.btAddItem);
EditText edit = (EditText)view.findViewById(R.id.eAddItem); //Initialize the EditText outside of the click method
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return view;
}
And in the future I'd advice to give your variables more meaningful names, sometimes it takes you a little more coding but it is worth it.
Posting my comment as answer, as I'm pretty sure that is the issue:
The variable edit seems to be null. That is because when you call v.findViewById, you are actually calling it on the view that was clicked and NOT the fragment's view.
So you got two options:
Change the name of the fragment's view. eg. View v1 = inflater.inflate(R.layout.library, parent, false); and then change the line to v1.findViewById
Change the name of the argument of onClick. eg. public void onClick(View v1) {.
Hope that helps.

Categories