How to get the text entered in an edittext? - android

I want to get the data entered in an edittext of android fragment in that same fragment of android.
I want that input details and send to a ble device.
Code is here:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
setCancelable(false);
View view = inflater.inflate(R.layout.verification, null);
verify=(EditText)view.findViewById(R.id.verify);
Next =(Button) view.findViewById(R.id.next);
Cancel=(Button) view.findViewById(R.id.cancel);
Next.setOnClickListener(this);
Cancel.setOnClickListener(this);
appContext = AppContext.getContext();
mContext=getActivity();
appContext = AppContext.getContext();
mOnDataSendListener = appContext.getOnDataSendListener();
timer();
Time=(TextView) view.findViewById(R.id.time);
return view;
}
#Override
public void onClick(View view) {
if(view.getId()==R.id.next){
factoryReset();
}
else {
dismiss();
}
}

Get verify data when you call method factoryReset() & send data as a parameter. Use below line to getText from editText:
verify.getText().toString()
Try with below code :
#Override
public void onClick(View view) {
if(view.getId()==R.id.next){
factoryReset(verify.getText().toString());
}
else {
dismiss();
}
public void factoryReset(String str1){
Log.e("VERIFY_DATA",""+str1);
}

Related

two onClick view in fragment for different purpose

My project needs two onClick event. One is for image browse and another is to submit. When I add two onClick event error is generated 'onClick(View)' is already defined in 'com.' When I search solution of this problem, It is suggested to combine two method with same parameters, but how ?
public class News_Yeb extends Fragment implements OnClickListener {
Button bt_register;
TextInputLayout til_name, til_username;
ImageView iv_profile;
String name, username, password, email, mobile, profile, confirm;
RequestQueue requestQueue;
boolean IMAGE_STATUS = false;
Bitmap profilePicture;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View RootView = inflater.inflate(R.layout.news_yeb, container, false);
til_name = RootView.findViewById(R.id.til_name_reg);
til_username = RootView.findViewById(R.id.til_username_reg);
bt_register = RootView.findViewById(R.id.bt_register);
iv_profile = RootView.findViewById(R.id.im_profile);
bt_register.setOnClickListener(this);
iv_profile.setOnClickListener(this);
return RootView;
}
public void onClick(View iv_profile) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1000);
}
#Override
public void onClick (View bt_register){
name = til_name.getEditText().getText().toString();
username = til_username.getEditText().getText().toString();
password = til_password.getEditText().getText().toString();
if (
validateName(name) &&
) .....
Dont use seperate onClick methods. Use this approach :
1) Implement class by View.OnClickListener
2) apply listener to yourButton.setOnClickListener(this) OR yourImage.setOnClickListener(this);
3) implement onClick method:
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.yourButton1:
//do your stuff
break;
case R.id.yourImage:
//do your stuff
break;
}
}
In one of the activities you might have
android:onClick = "onClick"
Replace one of these by, for instance,
android:onClick = "onClick2"
And rename the corresponding onClick method to onClick2:
public void onClick(View iv_profile){
...
}
public void onClick2 (View bt_register){
...
}

Fragment,DialogFragment Issue

I am calling dialog fragment from FragmentA and returning some values to fragmentA. Now issue is whenever i go to another fragmentB from same fragmentA and return to it my dialog fragment values get cleared.
when i click on consultant doctor textview, a dialog opens (Pic 2). On Selecting an item (Pic 2),returns a value back to FragmentA. Pic 3 is a Fragment B which opens on same activity. But when i click on cross button on pic 3 and popBackStack , my value for consult doctor clears shown in Pic 4.
Pic 4 is an ISSUE
DialogFragment
#Override
public void onStart() {
super.onStart();
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
getDialog().getWindow().setGravity(Gravity.CENTER);
getDialog().setCancelable(false);
getDialog().setCanceledOnTouchOutside(false);
getDialog().closeOptionsMenu();
}
#Override public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable #Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
View rootView = inflater.inflate(R.layout.consultant_doc_dialog, container, false);
recyclerView = (RecyclerView)rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);
adapter = new ConsultantDoctAdapter(getContext(),this);
adapter.getDocList().addAll(new ArrayList<DoctorList>());
recyclerView.setAdapter(adapter);
adapter.getDocList().clear();
adapter.getDocList().addAll(list);
adapter.notifyDataSetChanged();
close = (ImageButton)rootView.findViewById(R.id.bt_close);
close.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
getDialog().dismiss();
}
});
//cityEditText.setOnQueryTextListener(onQueryTextListener);
return rootView;
}
Fragment
#Nullable #Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_create_leads, container, false);
ButterKnife.bind(this, view);
setRetainInstance(true);
init();
setPicker();
setSpinnerListener();
btCheckCalendar.setOnClickListener(this);
etCityId.setOnClickListener(this);
etConsultingDocId.setOnClickListener(this);
btSubmit.setOnClickListener(this);
tvClientReferral.setOnClickListener(this);
etSalesPerson.setText(sharedPref.getString(AppConstants.PREFERENCE_USER_NAME, ""));
etZone.setText(sharedPref.getString(AppConstants.USER_ZONE, ""));
etAreaCode.setText(sharedPref.getString(AppConstants.USER_AREA_CODE, ""));
setSpinner();
getConsultantDoctorList();
return view;
}
Fragment B callBack:
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_main, new MyCalendarFragment())
.addToBackStack("calendarFragment")
.commit();
DialogCallack:
ConsultantDocDialogFragment consultantDocDialog = new ConsultantDocDialogFragment();
consultantDocDialog.setParameter(getContext(), this, doclist);
consultantDocDialog.show(getActivity().getSupportFragmentManager(),
ConsultantDocDialogFragment.class.getSimpleName());
break;
Please help me so that i can able to save state of values got from dialog fragment.
Please find the following code it may help you-
This is Fragment Code where you can get CallBack from Dialog Fragment-
HomeFragment.java
public class HomeFragment extends Fragment implements AlertDFragment.Callback {
private static final int DIALOG_FRAGMENT = 100;
Button alertdfragbutton;
private View rootView;
public HomeFragment() {
}
public static HomeFragment newInstance() {
return new HomeFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
initUI(rootView);
return rootView;
}
private void initUI(View rootView) {
alertdfragbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
AlertDFragment alertdFragment = new AlertDFragment();
alertdFragment.setTargetFragment(HomeFragment.this, DIALOG_FRAGMENT);
// Show Alert DialogFragment
alertdFragment.show(getChildFragmentManager(), "Alert Dialog Fragment");
}
});
}
#Override
public void accept() {
Log.e("Home ", "OK");
}
#Override
public void decline() {
}
#Override
public void cancel() {
Log.e("Home ", "CANCEL");
}
}
Here is Dialog Fragment where we declare CallBack with methods-
public class AlertDFragment extends DialogFragment {
Callback callback;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callback = (Callback) getTargetFragment();
return new AlertDialog.Builder(getActivity())
// Set Dialog Icon
.setIcon(R.drawable.androidhappy)
// Set Dialog Title
.setTitle("Alert DialogFragment")
// Set Dialog Message
.setMessage("Alert DialogFragment Tutorial")
// Positive button
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
callback.accept();
// Do something else
//getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
}
})
// Negative Button
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
callback.cancel();
// Do something else
// getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
}
}).create();
}
public static interface Callback {
public void accept();
public void decline();
public void cancel();
}
}
A simple way to return values from DialogFragment is using setTargetFragment for calling a fragmentB creation, then return data to getTargetFragment (if not null). In fragmentA you can receive data through onActivityResult.
Another way is using SharedPreferences. You can get a new value with onResume or onHiddenChanged.
Instead of using the "Fragment Transition" why don't you just POP-UP your custom view
Just Create a global reference of
Dialogue dialogue
View popupView
and on click of whatever textview button etc.
you can just call a method like
void popup(){
popupView = LayoutInflater.from(getActivity()).inflate(R.layout.your_calenderlayout, null);
//suppose you have TextView cal_textview in popUp view i.e, your_calenderlayout
cal_textview = (TextView ) popupView.findViewById(R.id.cal_textview);
dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(true);
dialog.setContentView(popupView); //and just add your popUpview
// For setting backgroung
/*dialog.getWindow().setBackgroundDrawableResource(android.R.color.Transparent);
*/
//For setting the width or height of popup
/*WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER;
dialog.getWindow().setAttributes(lp);*/
dialog.show();
}
and on dismiss of popUp or on click of the view inside popupView you set the value of variables or member inside the fragment directly
Hope this will help
You can use Shared prefs or sqlite to get your values and if you think its use less to save your temporary data in share prefs or sqlite Then Singleton model is a good option .. i believe we should follow KISS
design principle :P

Shared Preferences not working in Fragment

I have this App where I'm trying to store a button clicked state in a Fragment. But no matter how much I try, nothing seems to be getting stored. My code definitely seems alright.
public class ClubHome extends Fragment {
ImageView bell,bellring;
TextView beltext,belringtext;
SharedPreferences saved_values;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.club_home, container, false);
Bundle args = getArguments();
final String index = args.getString("club", "Party");
saved_values = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
bell= (ImageView) view.findViewById(R.id.bell);
bellring= (ImageView) view.findViewById(R.id.bellring);
beltext= (TextView) view.findViewById(R.id.bellmsg);
belringtext= (TextView) view.findViewById(R.id.bellringmsg);
bell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
belringtext.setVisibility(View.VISIBLE);
bellring.setVisibility(View.VISIBLE);
bell.setVisibility(View.INVISIBLE);
beltext.setVisibility(View.INVISIBLE);
SharedPreferences.Editor editor=saved_values.edit();
editor.putBoolean(index,true);
editor.apply();
editor.commit();
}
});
bellring.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
belringtext.setVisibility(View.INVISIBLE);
bellring.setVisibility(View.INVISIBLE);
bell.setVisibility(View.VISIBLE);
beltext.setVisibility(View.VISIBLE);
SharedPreferences.Editor editor=saved_values.edit();
editor.putBoolean(index,false);
editor.apply();
editor.commit();
}
});
boolean stat = saved_values.getBoolean(index,false);
if (stat){
belringtext.setVisibility(View.INVISIBLE);
bellring.setVisibility(View.INVISIBLE);
bell.setVisibility(View.VISIBLE);
beltext.setVisibility(View.VISIBLE);
} else {
belringtext.setVisibility(View.VISIBLE);
bellring.setVisibility(View.VISIBLE);
bell.setVisibility(View.INVISIBLE);
beltext.setVisibility(View.INVISIBLE);
}
}
}
Your implementation of saving data in SharedPreference is wrong.
You need to get your preference attribute first.
SharedPreference pref = getActivity().getSharedPreferences("MY_PREFERENCES", Activity.MODE_PRIVATE);
Now in the onClickListener of your buttons do something like this to save the desired value.
bell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// .. Set visibility of items.
pref.edit().putBoolean("INDEX", true).apply();
}
});
To get the stored value of INDEX from SharedPreference you need to do something like this
boolean indexStatus = pref.getBoolean("INDEX", false); // false is the default value if nothing is returned.

android studio edittext field value conversion

I have a fragment with a EditText and save button. when user click the save button, it should check whether the edittext value is out of range or the same data type. For this case, the value type should be "FLOAT" and range is "0.00 - 1000.00".
here's my code for the fragment.java.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.field_fragment,container, false);
int field = getArguments().getInt("field");
//Modify label
// TextView fieldLabel = (TextView)v.findViewById(field);
//fieldLabel.setText(MainActivity.pageNames[field]);
return v;
}
public void onStart() {
super.onStart();
//---Button view---
Button save = (Button)
getActivity().findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
Float conductivity = Float.parseFloat(conductivity_field.getText().toString());
if (conductivity > 0.F && conductivity < 1000.F) {
Toast.makeText(getActivity(), "The value is correct", Toast.LENGTH_SHORT).show();
} else {
//conductivity_field.setText(R.string.conductivity_field);//set text of the edittext back to the hint
Toast.makeText(getActivity(), "Wrong value for float", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
Toast.makeText(getActivity(), "Error converting values. Please enter correct value.", Toast.LENGTH_SHORT).show();
}
}
});
}
So i'm trying to display these errors but when i click it , it ignores the if condition and catches the exception and displays "error converting values msg...."
is there any other way?
Replace you code by this code ->
EditText conductivity_field;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.field_fragment,container, false);
conductivity_field = (EditText) v.findViewById(R.id.conductivity_value);
int field = getArguments().getInt("field");
//Modify label
// TextView fieldLabel = (TextView)v.findViewById(field);
//fieldLabel.setText(MainActivity.pageNames[field]);
return v;
}
public void onStart() {
super.onStart();
//---Button view---
Button save = (Button)
getActivity().findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
Float conductivity = Float.parseFloat(conductivity_field.getText().toString());
if (conductivity > 0.F && conductivity < 1000.F) {
Toast.makeText(getActivity(), "The value is correct", Toast.LENGTH_SHORT).show();
} else {
//conductivity_field.setText(R.string.conductivity_field);//set text of the edittext back to the hint
Toast.makeText(getActivity(), "Wrong value for float , BITCH", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
Toast.makeText(getActivity(), "Error converting values. Please enter correct value.", Toast.LENGTH_SHORT).show();
}
}
});
}
Button save;
Edittext conductivity_field;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.field_fragment, container, false);
initViews(view);
return view;
}
public void initViews(View v) {
conductivity_field = (EditText) v.findViewById(R.id.conductivity_value);
save= (Button) v.findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Float conductivity = Float.parseFloat(edittext.getText().toString());
if (conductivity > 0f && conductivity < 1000f) {
Toast.makeText(getActivity(), "The value is correct", Toast.LENGTH_SHORT).show();
} else {
//conductivity_field.setText(R.string.conductivity_field);//set text of the edittext back to the hint
Toast.makeText(getActivity(), "Wrong value for float", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Error converting values. Please enter correct value.", Toast.LENGTH_SHORT).show();
}
}
});
}
initialize the edittext to onCreateView method of fragment and use the reference of edittext to get the entered value,
what you are doing, initializing a new edittext named as conductivity_field and by default its value is blank so you are getting exception while parsing edittext value to float

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

Categories

Resources