Passing values between fragments while using viewpager in android - java

I want to create a sign up form where the form has been divided into three fragments.There is a next button in the fragment which causes the viewpager to move to the next fragment.But i want to pass values between the fragments how do i do that?
The main class:
package pl.looksok.viewpagerdemo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class MainActivity extends FragmentActivity {
ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager)findViewById(R.id.myViewPager);
pager.setAdapter(pageAdapter);
}
public void selectFragment(int position){
pager.setCurrentItem(position, true);
// true is to animate the transaction
}
}
The first fragment:
package pl.looksok.viewpagerdemo;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class FragmentBlue extends Fragment {
Button btnnext1;
RelativeLayout frag1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
btnnext1=(Button) view.findViewById(R.id.btnnext1);
frag1=(RelativeLayout) view.findViewById(R.id.frag1);
btnnext1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity)getActivity()).selectFragment(1);
}
});
return view;
}
}
The second fragment:
package pl.looksok.viewpagerdemo;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class FragmentGreen extends Fragment {
Button btnnext2;
RelativeLayout frag2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_green, container, false);
btnnext2=(Button) view.findViewById(R.id.btnnext2);
frag2=(RelativeLayout) view.findViewById(R.id.frag2);
btnnext2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity)getActivity()).selectFragment(2);
}
});
return view;
}
}
The third fragment:
package pl.looksok.viewpagerdemo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v4.app.Fragment;
public class FragmentPink extends Fragment {
Button btnnext3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pink, container, false);
btnnext3=(Button) view.findViewById(R.id.btnnext3);
btnnext3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
}
I would place a submit button in the last fragment which would post data to the server,So the data in the first two fragments should be available in the last fragment.So i want to know how to pass data from the first two fragments to the last one?
Also is my approach a bad way of achieving the task?Would i be better of creating three different activities and using intent and bundle to pass data?

You can use SharedPreferences. Before you change the fragment save entered values:
SharedPreferences sp = getSharedPreferences("pref_name", MODE_PRIVATE);
SharedPreferences.Editor editor = mSharedPref.edit();
editor.putString("key", value);
editor.commit();
And in other fragment when you want to use saved value:
SharedPreferences sp = getSharedPreferences(MainActivity.PREF_NAME, MODE_PRIVATE);
String value = mSharedPref.getString("key", null);
if(value !=null){
//do something with value
}
Another approach is using interface-callback pattern. You can read more here.

Related

Android Studio: Unable to remove fragment

I'm trying to remove a fragment and it's not working.
I've been checking with logcat and it's noticing that the button's been clicked and that message is being passed to the main activity. I assume there's something wrong with my code but I can't figure out what that is. Would appreciate some help.
MainMenu.java
package com.example.android.learninstrumentation;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainMenu extends AppCompatActivity implements MainMenuStFrag.MainMenuStFragListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
//Create a new Fragment to be placed in the Activity layout
Fragment menuSiFragment = new MainMenuSiFrag();
Fragment menuStFragment = new MainMenuStFrag();
//Add the fragment to the 'fragment_container' layout
getSupportFragmentManager().beginTransaction().add(R.id.fragment_type_si_container, menuSiFragment).commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_type_st_container, menuStFragment).commit();
}
//The user clicked 'expand' from MainMenuStFrag. Remove MainMenuSiFrag.
public void onExpandClick () {
Log.i("MainMenu", "Click message received");
Fragment oldFragment = new MainMenuSiFrag();
getSupportFragmentManager().beginTransaction().remove(oldFragment).addToBackStack(null).commit();
}
public void onCheckboxClick() {
}
}
MainMenuStFrag.java
package com.example.android.learninstrumentation;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
public class MainMenuStFrag extends Fragment implements View.OnClickListener{
MainMenuStFragListener mCallback;
//Inflate the layout and set buttons for this fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Store the Fragment in the mainMenu variable
View mainMenu = inflater.inflate(R.layout.main_menu_st_fragment, container, false);
//Define the buttons and set onClickListeners
ImageView expand = mainMenu.findViewById(R.id.mainMenu_imageView_SelectTopics);
expand.setOnClickListener(this);
CheckBox checkBox = mainMenu.findViewById(R.id.mainMenu_CheckBox_SelectAllTopics);
checkBox.setOnClickListener(this);
return mainMenu;
}
//Interface for communication with container Activity
public interface MainMenuStFragListener {
void onExpandClick();
void onCheckboxClick();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
//This makes sure the container Activity has implemented the callback interface.
// If not, it throws an exception.
try {
mCallback = (MainMenuStFragListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
//onClick actions
#Override public void onClick(View v) {
switch (v.getId()) {
//Remove the other 'type' item
case R.id.mainMenu_imageView_SelectTopics:
Log.i("MainMenuStFrag", "Topics>Expand=Clicked");
mCallback.onExpandClick();
break;
case R.id.mainMenu_CheckBox_SelectAllTopics:
mCallback.onCheckboxClick();
break;
}
}
}
MainMenuSiFrag.java
package com.example.android.learninstrumentation;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainMenuSiFrag extends Fragment {
//Inflate the layout for this fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainMenu = inflater.inflate(R.layout.main_menu_si_fragment, container, false);
return mainMenu;
}
}
You have created new instance of Fragment for remove Fragment
public void onExpandClick () {
Log.i("MainMenu", "Click message received");
Fragment oldFragment = new MainMenuSiFrag();
getSupportFragmentManager().beginTransaction().remove(oldFragment).addToBackStack(null).commit();
}
instead on that Find a fragment and remove it from container
Fragment oldFragment=getSupportFragmentManager().findFragmentById(R.id.fragment_type_si_container);
if(oldFragment!=null && oldFragment instanceof MainMenuSiFrag)
{
getSupportFragmentManager()
.beginTransaction().
remove(oldFragment).commit();
}

i have some problems in java Class i cant get EditText as string

package com.example.dato.task;
import android.app.DialogFragment; import android.os.Bundle; import
android.support.annotation.Nullable; import
android.view.LayoutInflater; import android.view.View; import
android.view.ViewGroup; import android.view.Window; import
android.widget.Button; import android.widget.EditText; /** * Created
by DATO on 2/17/2018. */
public class DialogClass extends DialogFragment{
public DialogClass(){}
String s;
String s1;
#Nullable
#Override
public View onCreateView( LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
final View dialogView= View.inflate(getActivity(), R.layout.dialog, null);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
final EditText e1 = dialogView.findViewById(R.id.text1);
final EditText e2= dialogView.findViewById(R.id.text2);
Button bt = dialogView.findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
s = e1.getText().toString();
s1 = e2.getText().toString();
dismiss();
}
});
return dialogView;
}
}
It's probably that in your dialog.xml layout you haven't the editTexts with the IDs "text1" and "text2".
The IDs can be different.

why method getBackStackEntryCount always return 0

I need to count my fragment, I used getbackstackentrycount, but it always return 0. Can someone tell me whats wrong with my code?
here my code MainActivity.java
package com.example.bams.taskagain;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.bams.taskagain.Fragment.FragmentOne;
public class MainActivity extends AppCompatActivity {
Button btn;
FragmentManager fm = getFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.fragOne);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fm.beginTransaction().add(R.id.content, new FragmentOne()).addToBackStack("aa").commit();
//Toast.makeText(getBaseContext(), "text", Toast.LENGTH_LONG).show();
}
});
}
}
and here is my fragment class
package com.example.bams.taskagain.Fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.bams.taskagain.R;
/**
* Created by jack on 25/02/2017.
*/
public class FragmentOne extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Total back stack "+ ((AppCompatActivity)getActivity()).getSupportFragmentManager().getBackStackEntryCount());
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one,container,false);
return rootView;
}
}
can someone help me with my code?
I just want to get the BackStack count that my fragement has.
You're using android.app.Fragment and android.app.FragmentManager but using getSupportFragmentManager() to get back stack entry count.
Use
getFragmentManager().getBackStackEntryCount()
getFragmentManager() is used if your fragment is android.app.Fragment and getSupportFragmentManager() if your fragment is android.support.v4.fragment.
For more info on these fragments, take a look at Difference between android.app.Fragment and android.support.v4.app.Fragment

cannot resolve method show(android.support.v4.app FragmentManager,java.lang.string)

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
/**
* Created by jamie on 9/12/2015.
*/
public class PlayersFragment extends DialogFragment {
ListView lv;
String[] players = {"arteta", "costa", "reid", "degea", "rooney", "terry"};
int[] images = {R.drawable.arteta, R.drawable.costa, R.drawable.reid, R.drawable.degea,
R.drawable.rooney, R.drawable.terry};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog, container, false);
//initialize listview
lv = (ListView) rootView.findViewById(R.id.listView1);
//set dialog title
getDialog().setTitle("Soccer SuperStars");
//create adapter obj and set list view to it
Adapter adapter = new Adapter(getActivity(), players, images);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
Toast.makeText(getActivity(), players[pos], Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
Trying to create a ListView fragment in android studio and getting
error
cannot resolve method show(android.support.v4.app
FragmentManager,java.lang.string)
the error is on the p.show(fm,"Players Fragment) underlined in red, tried to resolve this but getting nowhere, i would really appreciate a solution to this! thank you
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
Button showBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FragmentManager fm =getSupportFragmentManager();
final PlayersFragment p=new PlayersFragment();
showBtn=(Button)findViewById(R.id.button1);
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
p.show(fm,"Players Fragment"); //error is here
}
});
}
}
I suppose you are using android.app.DialogFragment and not android.support.v4.app.DialogFragment. Just extend PlayersFragment from support library's android.support.v4.app.DialogFragment. Or, if you are not targeting old devices, you can change getSupportFragmentManager() to getFragmentManager()
You have to import android.support.v4.app.DialogFragment on the class PlayersFragment and then change getSupportFragmentManager() to getFragmentManager().

ViewPager inside a Fragment (NestedFragments)

My app has the main activity with a Navigation Drawer, that allow the application to navigate between Fragments. Each item list of the navigation drawer shows a fragment.
In one of those Fragment I want a ViewPager, and here is where I got stuck. If I'm not wrong, this is a Fragment inside another Fragment (Nested Fragments) but I can't make this work.
This is the code of the fragment that contains the ViewPager
Seccion1.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class Seccion1 extends Fragment {
ViewPager vp;
private List<android.support.v4.app.Fragment> getFragments(){
List<android.support.v4.app.Fragment> list = new ArrayList<android.support.v4.app.Fragment>();
list.add(ModelFragment.newInstance("Hola como andas", "descriociones"));
list.add(ModelFragment.newInstance("0895452125x", "#FFFFEF59"));
list.add(ModelFragment.newInstance("22 Mart", "#FF9C63FF"));
list.add(ModelFragment.newInstance("Sak", "#72a83b"));
list.add(ModelFragment.newInstance("Android Studio", "#a83b97"));
return list;
}
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.seccion1, container, false);
vp = (ViewPager)rootView.findViewById(R.id.vp);
//vp.setPageTransformer(true, new RotateDownTransformer());
ControllerFragment cf = new ControllerFragment(getChildFragmentManager(), getFragments());
vp.setAdapter(cf);
return rootView;
}
}
I don't know how to fix this line:
ControllerFragment cf = new ControllerFragment(getChildFragmentManager(), getFragments());
Here the ControllerFragment code
ControllerFragment.java
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.List;
public class ControllerFragment extends FragmentPagerAdapter {
List<Fragment> fragments;
Context context;
public ControllerFragment(FragmentManager fm, List<Fragment> fragments){
super(fm);
this.fragments = fragments;
}
public Fragment getItem(int position){
return fragments.get(position);
}
public int getCount(){
return fragments.size();
}
public Object instantiateItem(View view, int position){
RelativeLayout relativeLayout = (RelativeLayout)view.inflate(context, R.layout.custom_fragment, null);
TextView tv_text = (TextView)relativeLayout.findViewById(R.id.tv_text);
TextView tv_description = (TextView)relativeLayout.findViewById(R.id.tv_description);
((ViewPager) view).addView(relativeLayout);
return relativeLayout;
}
}
Change this
import android.app.Fragment;
to
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

Categories

Resources