Spinner Fragment continually crashes - java

I am making a program that will include a Spinner within a fragment rather than an activity. I have researched why this may be crashing, but to no avail. My initial concern was a .getView().findViewById(), but now I'm not so sure that's the problem because . Here's the code.
public class Add extends Fragment {
public Add() {
// Required empty public constructor
}
ArrayList<String> ingredients = new ArrayList<>();
SpinnerDialog spinnerDialog;
Button add;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
add = (Button) getView().findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinnerDialog.showSpinerDialog();
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spinnerDialog = new SpinnerDialog(getActivity(), ingredients, "Select An Ingredient");
spinnerDialog.bindOnSpinerListener(new OnSpinerItemClick() {
#Override
public void onClick(String Ingredient, int i) {
Toast.makeText(Add.super.getContext(), "Selected ", Toast.LENGTH_SHORT).show();
}
});

Without seeing the stack trace I cannot say for sure, but I suspect this line is crashing:
add = (Button) getView().findViewById(R.id.add);
This is because getView() will return the View instance returned by onCreateView()... but you're currently inside onCreateView(), so getView() will return null.
You can re-write your onCreateView() as follows and it should work.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_add, container, false);
add = (Button) root.findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinnerDialog.showSpinerDialog();
}
});
return root;
}

Related

How to get input from EditText in android java fragment

I am trying to get user input using EditText from fragment after pressing a button. For some reason the button is clickable but no data from EditText.
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtUserInput"/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/btnTest"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"/>
public class MainActivity extends AppCompatActivity {
TestFragment testFragment = new TestFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, testFragment)
.commit();
}
}
public class TestFragment extends Fragment {
Button btnTest;
EditText txtUserInput;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
btnTest = view.findViewById(R.id.btnTest);
txtUserInput = view.findViewById(R.id.txtUserInput);
String input = txtUserInput.getText().toString();
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), input, Toast.LENGTH_LONG).show();
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
Add gettext() inside your click listener
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { String input=txtUserInput.getText().toString()
Toast.makeText(getActivity(), input, Toast.LENGTH_LONG).show();
}
});
as you want data from edite text after clicking the button so once you click then on click event is triggered and then you should get data from edit field
you can do this thing like
and View is used to get root view for the fragment.
View view = inflater. Inflate(R.layout.fragment_test, container, false);
EditText editText = view.findViewById(R.id.txtUserInput);
Button btnTest = view.findViewById(R.id.btnTest);
String input ="";
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
input=editText.getText().toString()
}
});

Open activity from fragment instantly closed

Hello I want to move to another activity from my fragment. I ve tried almost every solution which I found, but after I press button my app is instantly closed. I am new in java, and i guess i need some help.
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
Intent intent;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
intent = new Intent(GalleryFragment.this.getActivity(), HomeFragment.class);
final Button btn = (Button) rootView.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent);
}
});
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
I'm assuming from this line:
intent = new Intent(GalleryFragment.this.getActivity(), HomeFragment.class);
That you're trying to launch a Fragment, not an Activity. In order to transition to another Fragment, replace your Intent with:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getFragmentManager()
.beginTransaction()
.replace(...) //Or add, depends on your use case
.commit();
}
});

How to send to texts to listview using fragment activity

I have created fragment activity using viewpager with two tabs, and created listview with two textviews. I want to sent the two texts from tab one to tab two as title and description. I have successfully sent the description, but I failed to send the title (]I can only send one text to listview).
My fragment_one.java :
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager = (ViewPager)view.findViewById(R.id.viewPager);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final ListView list=(ListView)view.findViewById(R.id.list_view);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
my fragment_two.java :
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_two, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(getActivity(), R.layout.single_item,R.id.tvdesc, arrayList);
listView.setAdapter(adapter);
}
protected void displayReceivedData(String message) {
arrayList.add(0,message);
adapter.notifyDataSetChanged();
}
}
You should use call back data from fragment_one to main activity , and send data from activity to fragment_two (and refresh view)
Callback fragment to activity you can use How to make a callback between Activity and Fragment?
and Fragment_two you can set this value in Activity,
EX,
private Fragment mFragmentTwo;
.........
mFragmentTwo= new Fragment();
and can set value by funtion : mFragmentTwo.displayReceivedData(yourString)

OnClick not triggered inside Fragment

Got two empty Activites(A and B), which just hold two fragments inside ViewPager of Activity A.
I do not have code errors, everything seems fine.
When I lunch my app and click on button, nothing happens.I was trying just to log something, but still nothing is happening.
I am using ButterKnife, and so far everything was perfect.I got almost same Fragment and it is performing fine, but OnClick inside Fragment B is not working.I tried to add some more OnClick methods, but none of them worked for me.XML looks good,looks almost same as fragment A.
Fragment B is not complex, it just three TextViews and Button.
Here is code for my fragment B:
public class ForgotPasswordFragmentComplete extends BaseFragment
implements BaseView {
private Realm realm;
private Email model;
#Bind(R.id.btn_resend)
AppCompatButton resendEmail;
#Inject
ForgotPasswordPresenter presenter;
#OnClick(R.id.btn_resend)
public void resendButton() {
Log.d("ResendOnclick", "Checking OnClickMethod ");
Realm realm2 = getRealm();
RealmQuery<Email> queryUserResend = realm2.where(Email.class);
Email resultResend = queryUserResend.findFirst();
ForgotPasswordPayload forgotPayload = new ForgotPasswordPayload(resultResend.getUsername());
this.presenter.subscribe(forgotPayload);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerForgotPasswordCompletedComponent.builder()
.applicationComponent(
((AndroidApplication) getActivity().getApplication()).getApplicationComponent())
.forgotPasswordCompletedModule(new ForgotPasswordCompletedModule())
.build()
.inject(this);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
protected void onCreateViewWidgetInitialization(View view) {
super.onCreateViewWidgetInitialization(view);
}
#Override
public void onStart() {
super.onStart();
getEmail();
}
public void getEmail(){
Realm realm = getRealm();
RealmQuery<Email> queryUser = realm.where(Email.class);
Email result1 = queryUser.findFirst();
resendEmailTxt = (AutoResizeTextView) getView().findViewById(R.id.resend_user_email);
if (resendEmailTxt != null) {
this.resendEmailTxt.setText(result1.getUsername());
}
}
#Override
public void onDestroy() {
super.onDestroy();
realm.close();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_forgot_password_fragment_complete, container, false);
}
#Override
protected int getFragmentLayoutId() {
return R.layout.fragment_forgot_password_fragment_complete;
}
You need to bind the fragment's view object before you can use it. Try putting the following code inside onCreateView() :
View rootView = inflater.inflate(R.layout.fragment_forgot_password_fragment_complete, container, false);
ButterKnife.bind(this, rootView);
return rootView;

Android java class onClickListener

How can I set an onClick listener for a button in layout_one? Where do I put the code? when I put it in the onCreateView it gives me an error.
public class LayoutOne extends Fragment {
Button button;
public static Fragment newInstance(Context context) {
LayoutOne f = new LayoutOne();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_one, null);
return root;
}
set Layout attribute android:clickable="true", android:focusable="true" and android:focusableInTouchMode="true" from xml or setClickable(true) from code. set onClickListener as:
((LinearLayout)findViewById(R.id.layout_one_id)).setClickable(true); ((LinearLayout)findViewById(R.id.layout_one_id)).setOnClickListener(layoutOnClickListener);
private OnClickListener layoutOnClickListener = new OnClickListener() {
public void onClick(View v) {
//Get Click here
}
};
It wont give any error if You will do it something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater
.inflate(R.layout.layout_one, null);
Button button_one=(Button)root.findViewById(R.id.button_one);// button_one is the id of the button in your xml file
button_one.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return root;
}
Don't know what your button is called, but in onCreateView() you do:
button = (Button)root.findViewById(R.id.layout_one_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//stuff goes in here
}
});
Your other option is to do it in xml and just make a method that uses it. For example, setting the Buttons android:onClick="onButtonClicked" attribute, in code your method would look like this
public void onButtonClicked(View v) { /*Stuff*/ }

Categories

Resources