get input from fragments - android

I have a ViewPager with 3 fragments in it, each fragment has a next and prev. button, and you can also swipe left and right to navigate through fragments. and although I'm able to get the input from each fragment when the next button is clicked, I sill can't figure out a way to get the input when the user scrolls between fragments.
this is the code in my first fragment:
public class signupfrag1 extends Fragment {
private TextInputEditText fName, lName;
public Spinner spncountry, spncity;
private Button next1;
private String vfName, vlName, vcountry, vcity;
private String method;
signupfrag1Listener activityCommander;
public interface signupfrag1Listener{
public void getDataFromFrag1(String fName, String lName, String countryName, String cityName);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander = (signupfrag1Listener) context;
}catch (ClassCastException e){
throw new ClassCastException(context.toString());
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.signupfrag1, container, false);
fName = (TextInputEditText) view.findViewById(R.id.edtFName);
lName = (TextInputEditText) view.findViewById(R.id.edtLName);
spncountry = (Spinner) view.findViewById(R.id.cmbCountry);
spncity = (Spinner) view.findViewById(R.id.cmbCities);
next1 = (Button) view.findViewById(R.id.btnNext2);
next1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vfName = fName.getText().toString();
vlName = lName.getText().toString();
if(vfName.equals("") || vfName.length()==1){
fName.setError("please enter a correct first name!");
}
else if(vlName.equals("") || vlName.length()==1){
lName.setError("Please enter a correct first name!");
}
else
startFrag2(view);
}
});}
public void startFrag2(View view){
activityCommander.getDataFromFrag1(vfName, vlName, vcity, vcountry);
}
this is the code from my main activity:
public class Main2Activityforfragments extends AppCompatActivity implements signupfrag1.signupfrag1Listener, signupfrag2.signupfrag2Listener {
private ViewPager fragsViewPager;
private SectionsPagerAdapter1 sectionsPagerAdapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2_activityforfragments);
fragsViewPager = (ViewPager) findViewById(R.id.fragsViewPager);
sectionsPagerAdapter1 = new SectionsPagerAdapter1(getSupportFragmentManager());
fragsViewPager.setAdapter(sectionsPagerAdapter1);
}
//this get called when the next button is clicked
#Override
public void getDataFromFrag1(String fName, String lName, String cityName, String countryName) {
if(fragsViewPager.getCurrentItem() == 0){
fragsViewPager.setCurrentItem(1);}
}

if you are in the first fragment then create ref. of interface and call its method and pass the values on Click what you want and it is needed to implement Two interface in SecondFragment. call its method in the First Fragment. you can create interface Two in SecondFragment
Two Second=new SecondFragment(); // it will be called on click of firstFragment which pass the value.
Second.two("Value one","Value two");
interface Two{
void two(String value,String value); // implement this inteface in SecondFragment and call it in FirstFragment
}
When you reach to second you get the value from the first fragment and continue with the third fragment as same.

Related

Get Can't pass null for argument 'pathString' in child() error

I having some trouble with how to use a Button to access another activity with data from firebase. I'm just getting an error "Can't pass null for argument 'pathString' in child()". But when I try in another activity with OnItemClick on a listview item it works. Why is that?
What I'm trying to do is: I have a activity with a listview that stores and get data from firebase. What I want is, if I click on one of the items in that listview I want a new activity with buttons, and these buttons will get me to another activity with a listview that are related to the first activity (related data). So the activity with the buttons are the same activity for every listview items i click on, like just a "dummy" activity. Is this possible?
Here is the code:
lvjobbinfo works fine, but add doesn't. I want lvjobbinfo and add to do the same.
public class MainActivity extends AppCompatActivity {
EditText etinfonavn;
ListView lvjobbinfo;
TextView tvjobbnavn;
Button add;
DatabaseReference databaseJOBBINFO;
List<Main> jobbinfo;
public static final String infonavn = "infonavn";
public static final String infoid = "infoid";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseJOBBINFO = FirebaseDatabase.getInstance().getReference().child("Jobbinfo");
lvjobbinfo = (ListView)findViewById(R.id.lvjobbinfo);
lvjobbinfo.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Main main = jobbinfo.get(i);
Intent intent = new Intent(getApplicationContext(), Notater.class);
intent.putExtra(infoid, main.getInfoId());
intent.putExtra(infonavn, main.getInfonavn());
startActivity(intent);
return true;
}
});
tvjobbnavn = (TextView)findViewById(R.id.tvjobbnavn);
etinfonavn = (EditText) findViewById(R.id.etinfonavn) ;
add = (Button)findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent add = new Intent(MainActivity.this, Notater.class);
startActivity(add);
}
});
Intent intent = getIntent();
jobbinfo = new ArrayList<>();
String id = intent.getStringExtra(Jobbliste.jobbId);
String navn = intent.getStringExtra(Jobbliste.jobbnavn);
tvjobbnavn.setText(navn);
databaseJOBBINFO = FirebaseDatabase.getInstance().getReference("Jobbinfo").child(id);
}
#Override
protected void onStart() {
super.onStart();
databaseJOBBINFO.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
jobbinfo.clear();
for (DataSnapshot infosnapshot : dataSnapshot.getChildren()) {
final Main main = infosnapshot.getValue(Main.class);
jobbinfo.add(main);
final listMain infolistadapter = new listMain(MainActivity.this, jobbinfo);
lvjobbinfo.setAdapter(infolistadapter);
infolistadapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to get values of edittext which is in fragment on button click which is in activity?

signup screen with of two different modules driver and customer
Hi everyone I am working in android from past one year but now I am creating an app in which am using fragments instead of activity even after serching from so many sites and blogs am unable to implement what I want.
My requirement is as you see on the image two radio button one for customer and one for driver so when user click on any one of options then signup screen appears which is on fragment and one button is there at bottom which is on activity so I want how to get all edittext value on button click so that i can send these values to the server. My main problem is getting the values of edittext fields on button click.
So any help will be appriciated.
thanks in advance
Try like this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.your_fragment, container, false);
this.initViews(rootView);
selectProfessionsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
whta_you_want_on_button_click();
}
});
}
private void initViews(View view) {
//define your edittext like FirstNameEditText = (EditText) view.findViewById(R.id.FirstNameEditText);
}
now define the whta_you_want_on_button_click() method
in your activity, put below code in your button's click event.
try {
Fragment rg = getSupportFragmentManager().findFragmentByTag("YourFragmentTag");
if (rg != null) {
EditText et = (EditText) ((YourFragment) rg).getView().findViewById(R.id.edittext);
String etValue = et.getText().toString();
}
} catch (Exception e) {
}
Your context will change from getApplicationContext() to getActivity.getApplicationContext() when you are referencing a fragment instead of an activity
You have to create your edittext in this fashion
While assigning the layout you need to assign in this way.
View view = inflater.inflate(R.layout.fragmentlayout,container,false);
And while assigning edittext you need to take it as below
EditText edt = (EditText) view.findViewById(R.id.yourid);
String str = edt.getText().toString();
So on button click you can get the edittext string easily from onClick method with above code.
You can use static keyword make all edittext static so you will get all edittext values in activity on button click.
in your fragment suppose MyFragment.java
public class MyFragment extends Fragment{
View rootView;
public static EditText edt;
public MyFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
init();
return rootView;
}
protected void init(){
edt = (EditText) rootView.findViewById(R.id.edt);
}
}
in your activity suppose MainActivity.java
public class MainActivity extends Activity{
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewByid(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String value = MyFragment.edt.getText().toString().trim();
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}catch(Exception e){}
}
});
}
}

Creating listener of a CustomDialog out of the class in Android

I am trying to create a listener of a button of a customdialog which extends DialogFragment class and I want to locate the listener of custom buttons out of customdialog fragment class .However when I try to call the view of CustomDialog Fragment then I am getting null exception. What I do is to create an new instance of the customdialog fragment in somewhere else and say
customdialog.getView().findViewById(R.id.custombutton);
but I am getting null.
public class CustomDialog extends DialogFragment {
public final int RES_NONE = -1;
private TextViewCustomFont dialogTitle, view2, dialogBodyBottom,
dialogBodyTop;
private EditTextCustomFont dialogEditText;
private ButtonCustomFont dialogLeftButton;
private ButtonCustomFont dialogRightButton;
private Typeface GothamBold, GothamMedium, GothamUltra;
private static int title1, bodyTop1, bodyBottom1, EditTextHint1,
leftButton1, rightButton1;
onSubmitListener mListener;
private Dialog dialog;
interface onSubmitListener {
void setOnSubmitListener(String arg);
}
public static CustomDialog newInstance(int title, int bodyTop,
int bodyBottom, int EditTextHint, int leftButton, int rightButton) {
title1 = title;
bodyTop1 = bodyTop;
bodyBottom1 = bodyBottom;
EditTextHint1 = EditTextHint;
leftButton1 = leftButton;
rightButton1 = rightButton;
CustomDialog frag = new CustomDialog();
return frag;
}
public ButtonCustomFont getDialogLeftButton() {
return dialogLeftButton;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dialog = new Dialog(getActivity());
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//dialog.setContentView(R.layout.dialog_layout);
//dialog.show();
initLayout();
return dialog;
}
private void initLayout(){
dialog.setContentView(R.layout.dialog_layout);
setDialogView();
setCustomDialog();
}
public void setDialogView(){
//Create an java object of each dialog view item
dialogTitle = (TextViewCustomFont) dialog.findViewById(R.id.custom_dialog_title);
dialogBodyTop = (TextViewCustomFont) dialog.findViewById(R.id.custom_dialog_body_top);
dialogBodyBottom = (TextViewCustomFont) dialog.findViewById(R.id.custom_dialog_body_bottom);
dialogEditText = (EditTextCustomFont) dialog.findViewById(R.id.custom_dialog_body_et);
dialogLeftButton = (ButtonCustomFont) dialog.findViewById(R.id.custom_dialog_body_btn_left);
dialogRightButton = (ButtonCustomFont) }
public class LoginSelectionFragment extends Fragment {
public static LoginSelectionFragment newInstance() {
LoginSelectionFragment fragment = new LoginSelectionFragment();
return fragment;
}
#Override
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_loginselection,
container, false);
}
I am trying to pull the dialogLeftButton of CustomDialog Fragment and assing a listener on it inside the LoginSelectionFragment.
Here is how it looks like after I added method 2. This a part of LoginSelectionFragment
private void TwoButtonTextEditTextDialog(){
String title = getResources().getString(R.string.invalid_info_header);
String body = getResources().getString(R.string.invalid_info_body);
String body2 = getResources().getString(R.string.hint_newemail);
String btn1 = getResources().getString(R.string.cancel_uppercase);
String btn2 = getResources().getString(R.string.ok_alert);
fragmentDialog = CustomDialog.newInstance(title, body, body2, RES_NONE, btn1, btn2);
fragmentDialog.setCustomDialogFragmentListener(mDialogClickListener);
fragmentDialog.show(getFragmentManager(), "");
}
private CustomDialog.CustomDialogFragmentListener mDialogClickListener = new CustomDialog.CustomDialogFragmentListener(){
#Override
public void onNegativeClick() {
// TODO Auto-generated method stub
fragmentDialog.dismiss();
}
#Override
public void onPositiveClick() {
// TODO Auto-generated method stub
fragmentDialog.dismiss();
}
};
#Override
public void onNegativeClick() {
// TODO Auto-generated method stub
}
#Override
public void onPositiveClick() {
// TODO Auto-generated method stub
}
You could create a method as setDialogButtonClickListener(CustomDialog.OnButtonClickListener clickListener); where CustomDialog.OnButtonClickListener is an inner static interface , that way you could listen to click events of the buttons from anywhere.
An example of this could look as below,
public class CustomDialog extends DialogFragment {
.....
public static CustomDialog newInstance(int title, int bodyTop,
int bodyBottom, int EditTextHint, int leftButton, int rightButton) {
CustomDialog frag = new CustomDialog();
Bundle args = new Bundle();
args.putInt("title", title);
......
frag.setArguments(args);
return frag;
}
...
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(title)
.setPositiveButton(android.R.string.ok, this)
.setNegativeButton(android.R.string.cancel, this)
....
.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
listener.onRightButtonClick();
default:
listener.onLeftButtonClick();
}
}
}
...
private CustomDialog.OnButtonClickListener mClickListener;
....
public void setDialogButtonClickListener(CustomDialog.OnButtonClickListener clickListener){
mClickListener = clickListener;
}
...
public static interface OnButtonClickListener {
public void onLeftButtonClick();
public void onRightButtonClick();
}
}
If you notice from the above sample I posted , I have besides solving your problem of setting the click listener on buttons also have introduced you with the Factory Design Pattern on Android , You can see that instead of creating static fields for the button title and Dialog title I've set them in the Bundle Argument and then Retrieve them in the Dialogs onCreate() method.
For more Best Practices of Fragment You can take a look here
Edit
Ok , for your help I am providing you a Glimpse of what your LoginSelectionFragment should look like.
public class LoginSelectionFragment extends Fragment implements CustomDialog.OnButtonClickListener {
......// Method 1
public void showDialog(String title , String message .....) {
CustomDialog dialog = CustomDialog.getInstance(title , message...);
dialog.setDialogButtonClickListener(this);
dialog.show(getSupportFragmentManager(), null);
}
public void onLeftButtonClick(){
...// do something on left button click of dialog
}
public void onRightButtonClick(){
// do something on right button click of dialog
..
}
// Method 2
public void showDialog2(String title , String message .....) {
CustomDialog dialog = CustomDialog.getInstance(title , message...);
dialog.setDialogButtonClickListener(mDialogClickListener);
dialog.show(getSupportFragmentManager(), null);
}
private final CustomDialog.OnButtonClickListener mDialogClickListener = new CustomDialog.OnButtonClickListener() {
public void onLeftButtonClick(){
...// do something on left button click of dialog
}
public void onRightButtonClick(){
// do something on right button click of dialog
..
}
}
}
Now If you look at Method 1 , we have given parameters to showDialog() method so that you could reuse it for showing multiple times with different arguments ie., you could use this approach when you want to show the same dialog with different title , message etc
and in Method 2 we have provided an anonymous inner class for handling click events you could as many anonymous inner classes as you have different varieties of dialog ie dialog with different UI and different Event listeners in the same activity/fragment.
Enjoy!
Try to use this, (did not test this)
public class MyDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.input_warning)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
return builder.create();
}
}
and in your Activity fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.workout_a_fragment, container, false);
Button button = (Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
MyDialogFragment dialog = new MyDialogFragment();
dialog.show(fm, DIALOG_WARNING);
}
});}

Exception when showing a dialog after orientation change

I have an activity and a fragment inside it.inside fragment, there is a button, and on click of button a dialog shows.
Everything works, until user do a orientation change and click button after it.
IllegalStateException(cannot perform this action after onsaveinstancestate) occurs when user clicks button after orientation change. I'm using android support framework.
Anybody have any idea regarfing this?
Activity Code
public void openMoreDialog(String shareData, String link) {
DialogFragment dialog = new MoreDialog(shareData, link);
dialog.show(getSupportFragmentManager(), "MoreDialog");
}
Fragment Code
public void onAttach(Activity activity) {
super.onAttach(activity);
mControl = (ActivityControl)activity;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ImageButton moreButton = (ImageButton)v.findViewById(R.id.moreButton);
moreButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mControl.openMoreDialog(shareData, link);
}
});
return rootView;
}
FragmentDialog code
public class MoreDialog extends DialogFragment {
private String mShareData;
private String mLink;
public MoreDialog(String shareData, String link){
mShareData = shareData;
mLink = link;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.more_dialog, null);
Button openBtn = (Button)dialogView.findViewById(R.id.openBtn);
openBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openLink(mLink);
}
});
Button shareBtn = (Button)dialogView.findViewById(R.id.shareBtn);
shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
shareNews(mShareData);
}
});
builder.setView(dialogView);
return builder.create();
}
private void openLink(String link){
}
private void shareNews(String data){
}
}
Helpful link & solution how to:
https://stackoverflow.com/a/17413324/619673 and btw, constructor in fragment must be empty! Documentation:
http://developer.android.com/reference/android/app/Fragment.html
public Fragment ()
Added in API level 11
Default constructor.
Every fragment must have an empty constructor, so
it can be instantiated when restoring its activity's state. It is
strongly recommended that subclasses do not have other constructors
with parameters, since these constructors will not be called when the
fragment is re-instantiated; instead, arguments can be supplied by the
caller with setArguments(Bundle) and later retrieved by the Fragment
with getArguments().
Applications should generally not implement a constructor. The first
place application code an run where the fragment is ready to be used
is in onAttach(Activity), the point where the fragment is actually
associated with its activity. Some applications may also want to
implement onInflate(Activity, AttributeSet, Bundle) to retrieve
attributes from a layout resource, though should take care here
because this happens for the fragment is attached to its activity.

Android ViewPager using a single Fragment on multiple pages

I'm having a bit of trouble having the ViewPager displaying and running properly with a single fragment class.
So a bit of background. The Activity itself is supposed to allow users to answer questions in a survey. Each question consists of a question title, an input box, and a submit button. I've made a layout and a corresponding fragment (QuestionFragment) class to hold all of this.
My idea is to have the ViewPager hold a bunch of QuestionFragment's and the user will be able to swipe to the questions they would like to answer or edit. Basically each page will be using a QuestionFragment, but each will contain a unique question.
However my implementation doesn't look like its working out. The first page in the activity will have the UI set up (page 1) but the rest of the pages will have the default layout xml applied.
Note: at the moment I'm trying to set up the UI with the index number. You can ignore the Question[] array and any reference to it as the UI doesnt use it at this time. However I do try to set the typeface, which only works on the first page. You can take a look at the screenshots at the bottom, "How many moons does Saturn have" is the default xml in the layout. I've also noticed that the textview displays question 9, instead of 1.
Here is the fragment
public class SurveyTakerFragment extends Fragment {
private Question question;
private int index;
private TextView tv_question_title;
private EditText et_sms_response;
private Button btn_submit_response;
private SharedPreferences sharedPrefs;
private Typeface typeface;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_question, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setup();
}
void setup(){
Activity activity = getActivity();
tv_question_title = (TextView) activity.findViewById(R.id.tv_question_title);
et_sms_response = (EditText) activity.findViewById(R.id.et_sms_response);
btn_submit_response = (Button) activity.findViewById(R.id.btn_submit_response);
tv_question_title.setTypeface(typeface);
tv_question_title.setText("Question: " + index);
//TODO: Set question title.
//TODO: Pre-fill previous answer if any.
btn_submit_response.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String response = et_sms_response.getText().toString();
//TODO: Submit response.
}
});
}
public void setQuestion(Question question, int index){
this.question = question;
this.index = index;
}
public void setSharedPrefs(SharedPreferences sharedPrefs){
this.sharedPrefs = sharedPrefs;
}
public void setTypeface(Typeface typeface){
this.typeface = typeface;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
}
Here is the adapter:
public class SurveyTakerAdapter extends FragmentPagerAdapter{
private Question[] questions;
private SharedPreferences sharedPrefs;
private Typeface typeface;
public SurveyTakerAdapter(FragmentManager fm, Question[] questions,
SharedPreferences sharedPrefs, Typeface typeface) {
super(fm);
this.questions = questions;
this.sharedPrefs = sharedPrefs;
this.typeface = typeface;
}
#Override
public Fragment getItem(int index) {
SurveyTakerFragment surveyTakerFragment = new SurveyTakerFragment();
surveyTakerFragment.setQuestion(questions[index], index);
surveyTakerFragment.setSharedPrefs(sharedPrefs);
surveyTakerFragment.setTypeface(typeface);
return surveyTakerFragment;
}
#Override
public int getCount() {
return questions.length;
}
#Override
public CharSequence getPageTitle(int position) {
return "Question: " + (position + 1);
}
}
Pager Activity
public class SurveyTaker extends FragmentActivity{
private final String APP_DATA = "appData";
private SurveyTakerAdapter surveyTakerAdapter;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_survey);
Question[] questions = new Question[10];
FragmentManager fragmentManager = getSupportFragmentManager();
SharedPreferences sharedPrefs = getSharedPreferences(APP_DATA, MODE_PRIVATE);
Typeface robot = Typeface.createFromAsset(getAssets(), "Roboto-Thin.ttf");
surveyTakerAdapter = new SurveyTakerAdapter(fragmentManager, questions, sharedPrefs, robot);
viewPager = (ViewPager) findViewById(R.id.vp_survey_taker);
viewPager.setOffscreenPageLimit(10);
viewPager.setAdapter(surveyTakerAdapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int index) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
}
I'm assuming this is the case because I'm using a single fragment to populate all the pages in the viewpager, but I don't know how else to go about this. Is my design bad? Or is there something im missing?
Any help would be greatly appreciated!
Thanks!
It looks like the R.id.tv_question_title, R.id.tv_question_title and R.id.tv_question_title views are part of your R.layout.fragment_question layout. You should be referencing those views through your SurveyTakerFragment instance using getView(), not through the Activity via getActivity(). You are also duplicating effort in onActivityCreated() and setup().
Replace your onActivityCreated() and setup() implementations with this:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setup();
}
void setup(){
View view = getView();
tv_question_title = (TextView) view.findViewById(R.id.tv_question_title);
et_sms_response = (EditText) view.findViewById(R.id.et_sms_response);
btn_submit_response = (Button) view.findViewById(R.id.btn_submit_response);
tv_question_title.setTypeface(typeface);
tv_question_title.setText("Question: " + index);
//TODO: Set question title.
//TODO: Pre-fill previous answer if any.
btn_submit_response.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String response = et_sms_response.getText().toString();
//TODO: Submit response.
}
});
}

Categories

Resources