How to get input from EditText in android java fragment - java

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

Related

how to replace the fragment1 from fragment2 from a button click of a dialog[NOT DIALOG FRAGMENT] (which is called by fragment1)

I am facing a problem where I am opening a dialog (Dialog 1) from fragment1 and there is a button (change) on Dialog1 on which if I click then: Dialog1 should be dismissed and on the same fragment1 should be replaced by fragment2(Another fragment)
public class PedigreeAnalysis extends Fragment //My Fragment1
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
showDialog();
}
// SHOW DIALOG FUNCTION IS SHOWN BELOW `
void showDialog() { //Function to show the dialog starts...
Dialog dialog= new Dialog(getActivity());
Button btn = dialog.findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Code for opening new fragment and dismissing the dialog.
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment1, new Fragment2()).commit();
dialog.dismiss();
}
});
}//Function Ends Here....
I have even tried the reverse logic of (dismissing the dialog first and then replacing it with the function but it also doesn't works) as :
dialog.dismiss();//First dismissing the dialog
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment1, new Fragment2()).commit();//Replacing the fragment
Follow this...
Fragment1:
public class Fragment1 extends Fragment {
private ItemClickListener itemClickListener;
private Button addButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// all the views are initialized here...
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
addButton.setOnClickListener(v -> {
if (itemClickListener != null) onItemClicked.onClicked(new Plan());
});
}
public Fragment1 setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
return this;
}
public interface ItemClickListener {
void onItemClicked(Plan plan);
}
}
In parent Activity Class
public class PlanActivity extends AppCompatActivity {
private Fragment1 fragment1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plan);
fragment1 = new Fragment1()
.setOnAddButtonClicked(this::openFragmentEditPlan);
openFragment1();
}
private void openFragment1() {
getSupportFragmentManager().beginTransaction()
//frameLayout_PlanActivity is the container of both fragments
.add(R.id.frameLayout_PlanActivity, fragment1)
.commit();
}
public void openFragmentEditPlan(Plan plan) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.frameLayout_PlanActivity, FragmentEditPlan.newInstance(plan))
.addToBackStack("Fragment Edit Plan")
.commit();
}
}

Need help getting a Toast to appear on a Tab Fragment

I'm trying to get a Toast to appear in a tabbed fragment when an EditText is left empty.
Here is my MainActivity's onCreate:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
}
My Tabbed Fragment works fine with this code:
public class SignupFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_signup, container, false);
}
}
But it doesn't work when creating the Toast like this:
public class SignupFragment extends Fragment {
EditText textFillCheck;
Button submitCheck;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
submitCheck = (Button) submitCheck.findViewById(R.id.signupBtn);
textFillCheck = (EditText) textFillCheck.findViewById(R.id.signupFirstName);
submitCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(textFillCheck.getText().toString())) {
Intent intent = new Intent(getActivity(), SignupFragment.class);
startActivity(intent);
Toast.makeText(getActivity(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}
else{Toast.makeText(getActivity(), textFillCheck.getText().toString(), Toast.LENGTH_LONG).show();
}
}
});
return inflater.inflate(R.layout.fragment_signup, container, false);
}
}
You're not accessing the views of your Fragment's layout so the layout you're returning in onCreateView() doesn't have your logic attached to it. You should set up your Fragment to look something like this:
public class SignupFragment extends Fragment {
EditText textFillCheck;
Button submitCheck;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
// Store a reference to your Fragment's inflated layout
View root = inflater.inflate(R.layout.fragment_signup, container, false);
// Use the reference to access your Fragment's views
submitCheck = (Button) root.findViewById(R.id.signupBtn);
textFillCheck = (EditText) root.findViewById(R.id.signupFirstName);
submitCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(TextUtils.isEmpty(textFillCheck.getText().toString())) {
Toast.makeText(getActivity(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), textFillCheck.getText().toString(), Toast.LENGTH_LONG).show();
}
}
});
// Return the inflated layout
return root;
}
}
I am amazed why your code is not having any error like VIEW DOES NOT EXIST or NULL POINTER EXCEPTION because
First, you change the activity before showing the Toast secondly you are inflating the layout after the initialization of views and not getting the context properly, Right way of doing what you are trying to achieve is using OnViewCreated() like this
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
submitCheck = (Button) view.findViewById(R.id.signupBtn);
textFillCheck = (EditText) view.findViewById(R.id.signupFirstName);
submitCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(textFillCheck.getText().toString())) {
Toast.makeText(getActivity(), "Please fill in all fields",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), SignupFragment.class);
startActivity(intent);
}
else{
Toast.makeText(getActivity(), textFillCheck.getText().toString(),
Toast.LENGTH_LONG).show();
}
}
});
}

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

Why is my code always receiving a null pointer exception when I have binded the element in to it? I am using Java in Android Studio

I am receiving java.lang.NullPointerException, although I have binded the element correctly.
Tried to check the ID of the element, it matches, but still I receive the same exception.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Text to Speech
tts = new TextToSpeech(this, this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
speakButton = view.findViewById(R.id.speakButton);
}
}
It should be running fine, But I am receiving the java.lang.NullPointerException
You button code should be declared in you fragment not in you activity as the button is in your fragment.xml. As you are accessing the button in onCreate method of the activity it will give nullpointer exception because you fragment's view is not yet rendered.The best practice is to access the view in onViewCreated function of your fragment.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Text to Speech
tts = new TextToSpeech(getActivity(), this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
}
void speakOut(){
}
The solution is to implement TextToSpeech.OnInitListener in the project and make the public variables to be private.
public class TranslatorFragment extends Fragment implements TextToSpeech.OnInitListener{
private Button speakButton; // public Button speakButton;
private TextToSpeech tts;
private EditText speechText; // public EditText speechText;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tts = new TextToSpeech(getActivity(), this);
speakButton = view.findViewById(R.id.speakButton);
speechText = view.findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
}
private void speakOut(){
String text = speechText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int status){
if(status == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.getDefault());
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(getActivity(), "Language not supported!", Toast.LENGTH_SHORT).show();
} else {
speakButton.setEnabled(true);
speakOut();
}
}
else
{
Toast.makeText(getActivity(), "Initilization failed!", Toast.LENGTH_SHORT).show();
}
}
public void onDestroy() {
if(tts != null){
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}

Spinner Fragment continually crashes

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

Categories

Resources