I have two fragment (AddAddressFragment,AddressFragment) and one DialogFragment. In my app i show alert box with radio button. If user choose anyone option, i want to pass that item to two fragment(AddressFragment and also AddAddressFragment). I can passed only one fragment(AddressFragment). How to pass the same value to another fragment(AddAddressFragment). I want to make list view in that AddAddressFragment
My code here:
RadioListAlert.java:
public class RadioListAlert extends DialogFragment {
CharSequence[] tag = { "Home", "Office", "Pg", "Others" };
private AddressListener addressListener;
private String itemClicked;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(true);
builder.setTitle("Please Tag Your Address").setSingleChoiceItems(tag, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getActivity(), tag[which],Toast.LENGTH_SHORT).show();
itemClicked = (String) tag[which];
}
}).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (addressListener != null)
addressListener.itemClicked(itemClicked);
//to dismiss the dialog after user choose an item and click ok, you can also add some validation before dismissing the dialog
dismiss();
}
}).setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
return builder.create();
}
public void setListener(AddressListener addressListener)
{
this.addressListener = addressListener;
}
public interface AddressListener
{
void itemClicked(String text);
}
}
AddressFragment.java:
public class AddressFragment extends Fragment implements RadioListAlert.AddressListener {
int position = 0;
EditText line1;
EditText line2;
EditText landmark;
AutoCompleteTextView cityText;
EditText zipcode;
Spinner country;
Spinner state;
RadioGroup tag;
Button savaddr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_address, container, false);
savaddr = (Button) view.findViewById(R.id.addrsave);
tag = (RadioGroup) view.findViewById(R.id.radioGroup);
line1 = (EditText) view.findViewById(R.id.line1);
line2 = (EditText) view.findViewById(R.id.line2);
cityText = (AutoCompleteTextView) view.findViewById(R.id.city_autoCompleteTextView);
zipcode = (EditText) view.findViewById(R.id.zipcode);
country = (Spinner) view.findViewById(R.id.countrySpinner);
state = (Spinner) view.findViewById(R.id.stateSpinner);
landmark = (EditText) view.findViewById(R.id.landmark);
// Get a reference to the AutoCompleteTextView in the layout
AutoCompleteTextView textView = (AutoCompleteTextView) view.findViewById(R.id.city_autoCompleteTextView);
// Get the string array
String[] city = getResources().getStringArray(R.array.city);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, city);
textView.setAdapter(adapter);
savaddr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String addr1 = line1.getText().toString();
String addr2 = line2.getText().toString();
String addr_city = cityText.getText().toString();
String addr_zipcode = zipcode.getText().toString();
String addr_country = country.getSelectedItem().toString();
String addr_state = state.getSelectedItem().toString();
//Field Validation
if (Utility.isNotNull(addr1) && Utility.isNotNull(addr2) && Utility.isNotNull(addr_city) && Utility.isNotNull(addr_zipcode) && Utility.isNotNull(addr_country) && Utility.isNotNull(addr_state)) {
if (Utility.line2_validate(addr2)) {
if (Utility.line2_validate(addr_city)) {
//Show alert box with radio button option
RadioListAlert objRadioListAlert=new RadioListAlert();
objRadioListAlert.setListener(AddressFragment .this);
objRadioListAlert.show(getActivity().getFragmentManager(), "Radio Alert");
Toast.makeText(getActivity().getApplicationContext(), "Success.", Toast.LENGTH_SHORT).show();
} else {
cityText.setError("Enter valid City");
}
} else {
line2.setError("Enter valid Address");
}
} else {
Toast.makeText(getActivity().getApplicationContext(), "Please fill the form, don't leave any field blank", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
#Override
public void itemClicked(String text) {
((AccountActivity) getActivity()).navigatetoAddAddressActivity(text);
}
}
AddAddressFragment.java:
public class AddAddressFragment extends Fragment implements RadioListAlert.AddressListener {
ImageView add;
ListView addressListView;
private ArrayList<String> strArr;
private ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_add_address, container,
false);
addressListView = (ListView) view.findViewById(R.id.address_list);
add = (ImageView)view.findViewById(R.id.add_address);
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//((AccountActivity) getActivity()).navigatetoAddAddressActivity();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
AddressFragment fragment = new AddressFragment();
transaction.replace(R.id.account_frame, fragment);
transaction.commit();
}
});
return view;
}
#Override
public void itemClicked(String text) {
Log.d("Welcome","Its worked");
Toast.makeText(getActivity().getApplicationContext(), "Item Clicked:" + text, Toast.LENGTH_SHORT).show();
strArr = new ArrayList<String>();
for (int i = 0; i < 2; i++) {
strArr.add(text + i);
adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1, strArr);
addressListView.setAdapter(adapter);
}
}
}
Please anyone help me!!
Thanks in advance!!!
You can use localbroadcast to send data between fragments
this is also handy when you want to send data from service to fragment or activity
how to use LocalBroadcastManager?
Related
I know there are similar questions but I couldn't find an answer to solve my problem.
I have a DialogUpdateEmail which I want to be opened from ProfileFragment. In the dialog I want to enter my new email and send it to my ProfileFragment in order to change it also in the database.
ProfileFragment.java :
import androidx.fragment.app.Fragment;
public class ProfileFragment extends Fragment implements SendInputEmail {
public static final int PROFILE_FRAGMENT = 1;
private static final String TAG = "ProfileFragment";
private TextView TVHello, TVUsernameMessage, TVusernameinfo, TVemailinfo, TVbirthdate;
public void sendInput(String input) {
Log.d(TAG, "sendInput: found incoming input: " + input);
TVemailinfo.setText(input);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
Button Bsignout = (Button) v.findViewById(R.id.signoutbutton);
Button Beditusername = (Button) v.findViewById(R.id.editusernamebutton);
Button Beditemail = (Button) v.findViewById(R.id.editemailbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: opening email dialog");
DialogUpdateEmail dialog = new DialogUpdateEmail();
dialog.setTargetFragment(ProfileFragment.this,PROFILE_FRAGMENT);
dialog.show(getActivity().getFragmentManager(), "DialogUpdateEmail");
}
});
return v;
}
DialogUpdateEmail.java :
public class DialogUpdateEmail extends DialogFragment implements SendInputEmail {
private static final String TAG = "DialogUpdateEmail";
SendInputEmail mHost = (SendInputEmail)getTargetFragment();
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.popup, container, false);
EditText UpdateEmail = (EditText) view.findViewById(R.id.emailinfoupdate);
Button Beditemail = (Button) view.findViewById(R.id.updatesavebutton);
Button Bcancelemail = (Button) view.findViewById(R.id.updatecancelbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: capturing input.");
String input = UpdateEmail.getText().toString();
Log.d(TAG, "input : "+input);
mHost.sendInput(input);
getDialog().dismiss();
}
});
return view ;
}
public void onAttach(Context context) {
super.onAttach(context);
try{
mHost = (SendInputEmail) getTargetFragment();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException : " + e.getMessage() );
}
}
#Override
public void sendInput(String input) {
}
}
SendInputEmail Interface :
public interface SendInputEmail {
void sendInput(String input);
}
My problem is that I have an error when I try to use setTargetFragment in ProfileFragment. It says that Profile Fragment is not a Fragment, I really don't know why.
From doc in here :
public class DialogUpdateEmail extends DialogFragment {
private DialogEditListener listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = requireActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View view = inflater.inflate(R.layout.popup, null);
builder.setView(view);
EditText UpdateEmail = (EditText) view.findViewById(R.id.emailinfoupdate);
Button Beditemail = (Button) view.findViewById(R.id.updatesavebutton);
Button Bcancelemail = (Button) view.findViewById(R.id.updatecancelbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
listener.onDialogEditClick(UpdateEmail.getText().toString());
DialogUpdateEmail.this.getDialog().dismiss();
}
}
});
Bcancelemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogUpdateEmail.this.getDialog().cancel();
}
});
return builder.create();
}
public interface DialogEditListener {
void onDialogEditClick(String email);
}
public void setListener(DialogEditListener listener) {
this.listener = listener;
}
}
We send the email from the dialog to the fragment using the observer/listener pattern.
And in your ProfileFragment just implement DialogEditListener and subscribe it to listen for click button in the dialog like so:
public class ProfileFragment extends Fragment
implements SendInputEmail, DialogUpdateEmail.DialogEditListener {
public static final int PROFILE_FRAGMENT = 1;
private static final String TAG = "ProfileFragment";
private TextView TVHello, TVUsernameMessage, TVusernameinfo, TVemailinfo, TVbirthdate;
public void sendInput(String input) {
Log.d(TAG, "sendInput: found incoming input: " + input);
TVemailinfo.setText(input);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
Button Bsignout = (Button) v.findViewById(R.id.signoutbutton);
Button Beditusername = (Button) v.findViewById(R.id.editusernamebutton);
Button Beditemail = (Button) v.findViewById(R.id.editemailbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: opening email dialog");
//show your dialog
DialogUpdateEmail dialogUpdateEmail = new DialogUpdateEmail();
dialogUpdateEmail.setListener(ProfileFragment.this);
dialogUpdateEmail.show(getActivity().getSupportFragmentManager(), "DialogUpdateEmail");
}
});
return v;
}
#Override
public void onDialogEditClick(String email) {
//use your email here
Toast.makeText(getContext(), "My email: " + email, Toast.LENGTH_SHORT).show();
}
}
public class fragment_oneway_flight extends Fragment {
private Spinner spinner1 ;
Context thiscontext;
private int mYear, mMonth, mDay, mHour, mMinute;
int countadult= 1;
int countchild= 0;
int countinfant= 0;
private ProgressDialog pDialog,pDialog1;
TextView quantity_adult_textview, quantity_child_textview, quantity_infant_textview, textview_city_slct_from_oneway, textview_city_slct_to_oneway;
private ImageButton increment_adult_Button, decrement_adult_Button, increment_child_Button, decrement_child_Button, increment_infant_Button, decrement_infant_Button;
private Button prcdtoonwyrslt;
public fragment_oneway_flight() {
// Required empty public constructor
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
thiscontext = container.getContext();
View rootView = inflater.inflate(R.layout.fragment_oneway_flight, container, false);
LinearLayout select_dep_date = (LinearLayout) rootView.findViewById(R.id.date_from_select_oneway);
select_dep_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment dFragment = new DatePickerFragment();
// Show the date picker dialog fragment
dFragment.show(getFragmentManager(), "Date Picker");
}
});
LinearLayout city_slct_from_oneway = (LinearLayout) rootView.findViewById(R.id.city_slct_from_oneway);
city_slct_from_oneway.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogBoxFragment DialogBoxFragment = new DialogBoxFragment ();
DialogBoxFragment.show(getFragmentManager(),"dialog");
}
});
LinearLayout city_slct_to_oneway = (LinearLayout) rootView.findViewById(R.id.city_slct_to_oneway);
city_slct_to_oneway.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogBoxFragment2 DialogBoxFragment2 = new DialogBoxFragment2 ();
DialogBoxFragment2.show(getFragmentManager(),"dialog2");
}
});
prcdtoonwyrslt = (Button) rootView.findViewById( R.id.prcdtoonwyrslt );
prcdtoonwyrslt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), activity_flight_result_oneway.class);
pDialog1 = new ProgressDialog(getActivity());
pDialog1.setMessage("Please Wait...");
pDialog1.setCancelable(false);
String countadult = quantity_adult_textview.getText().toString();
String countchild = quantity_child_textview.getText().toString();
String countinfant = quantity_infant_textview.getText().toString();
String selectedfromcity = textview_city_slct_from_oneway.getText().toString();
String selectedtocity = textview_city_slct_to_oneway.getText().toString();
intent.putExtra("adultsnos", countadult);
intent.putExtra("childsnos", countchild);
intent.putExtra("infantsnos", countinfant);
intent.putExtra("fromcity", selectedfromcity);
intent.putExtra("tocity", selectedtocity);
startActivity(intent);
}
});
// button function start
increment_adult_Button = (ImageButton) rootView.findViewById( R.id.increment_adult_Button );
decrement_adult_Button = (ImageButton) rootView.findViewById( R.id.decrement_adult_Button );
increment_child_Button = (ImageButton) rootView.findViewById( R.id.increment_child_Button );
decrement_child_Button = (ImageButton) rootView.findViewById( R.id.decrement_child_Button );
increment_infant_Button = (ImageButton) rootView.findViewById( R.id.increment_infant_Button );
decrement_infant_Button = (ImageButton) rootView.findViewById( R.id.decrement_infant_Button );
quantity_adult_textview = (TextView) rootView.findViewById(R.id.quantity_adult_textview);
quantity_child_textview = (TextView) rootView.findViewById(R.id.quantity_child_textview);
quantity_infant_textview = (TextView) rootView.findViewById(R.id.quantity_infant_textview);
increment_adult_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countadult++;
if(countadult>7){
countadult=7;
}
display(countadult);
}
});
decrement_adult_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countadult--;
if(countadult<1){
countadult=1;
}
display(countadult);
}
});
increment_child_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countchild++;
if(countchild>5){
countchild=5;
}
display(countchild);
}
});
decrement_child_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countchild--;
if(countchild<0){
countchild=0;
}
display(countchild);
}
});
increment_infant_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countinfant++;
if(countinfant>5){
countinfant=5;
}
display(countinfant);
}
});
decrement_infant_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countinfant--;
if(countinfant<0){
countinfant=0;
}
display(countinfant);
}
});
// button function end
setSpinnerContent( rootView );
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> id, View rootView, int pos, long arg3) {
if (pos == 0) {
Toast.makeText(getActivity().getApplicationContext(),
"Select Class", Toast.LENGTH_SHORT)
.show();
} else if (pos == 1) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Economy", Toast.LENGTH_SHORT)
.show();
} else if (pos == 2) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Premium Economy", Toast.LENGTH_SHORT)
.show();
} else if (pos == 3) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected Business", Toast.LENGTH_SHORT)
.show();
}else if (pos == 4) {
Toast.makeText(getActivity().getApplicationContext(),
"You have selected First Class", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getActivity().getApplicationContext(), "Nothing to select", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
private void setSpinnerContent( View rootView ) {
spinner1 = (Spinner) rootView.findViewById( R.id.spinner_flight );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.flight_class_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter( adapter );
}
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
/*
Initialize a new DatePickerDialog
DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener callBack,
int year, int monthOfYear, int dayOfMonth)
*/
DatePickerDialog dpd = new DatePickerDialog(getActivity(), R.style.DateDialog,this,year,month,day);
return dpd;
}
public void onDateSet(DatePicker view, int year, int month, int day){
// Do something with the chosen date
TextView dep_date_flight = (TextView) getActivity().findViewById(R.id.text_dep_date);
// Create a Date variable/object with user chosen date
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
Date chosenDate = cal.getTime();
// Format the date using style and locale
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
String formattedDate = df.format(chosenDate);
// Display the chosen date to app interface
dep_date_flight.setText(formattedDate);
}
}
private void display(int number) {
quantity_adult_textview.setText(String.valueOf(countadult));
quantity_child_textview.setText(String.valueOf(countchild));
quantity_infant_textview.setText(String.valueOf(countinfant));
}
public static class DialogBoxFragment extends DialogFragment {
//declaring variables
private ListView listviewforresults;
//Adapter for listview
ArrayAdapter<String> list1adapter;
//Edittext for search
EditText searchdata;
//ArrayList for listview
ArrayList<String> data=new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView1 = inflater.inflate(R.layout.fragment_city_select_flight, container, false);
prepareDummyData();
listviewforresults=(ListView)rootView1.findViewById(R.id.showdata);
searchdata=(EditText)rootView1.findViewById(R.id.searchdata);
//set data to Adapter
list1adapter=new ArrayAdapter<String>(getActivity(), country_list,R.id.results,data);
listviewforresults.setAdapter(list1adapter);
//search data when text changes in edittext
searchdata.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
list1adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
listviewforresults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String selectedFromList = (String) listviewforresults.getItemAtPosition(position).toString();
TextView textview_city_slct_from_oneway = (TextView) getActivity().findViewById(R.id.textview_city_slct_from_oneway);
textview_city_slct_from_oneway.setText(selectedFromList);
getDialog().dismiss();
}
});
getDialog().setTitle("dialog");
return rootView1;
}
public void prepareDummyData()
{
data.add("Chennai");
data.add("Mumbai");
data.add("Bangalore");
data.add("Madurai");
data.add("Coimbatore");
data.add("Newdelhi");
}
}
public static class DialogBoxFragment2 extends DialogFragment {
//declaring variables
private ListView listviewforresults2;
//Adapter for listview
ArrayAdapter<String> list2adapter;
//Edittext for search
EditText searchdata;
//ArrayList for listview
ArrayList<String> data=new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView2 = inflater.inflate(R.layout.fragment_city_select_flight2, container, false);
prepareDummyData2();
listviewforresults2=(ListView)rootView2.findViewById(R.id.showdata);
searchdata=(EditText)rootView2.findViewById(R.id.searchdata);
//set data to Adapter
list2adapter=new ArrayAdapter<String>(getActivity(), country_list,R.id.results,data);
listviewforresults2.setAdapter(list2adapter);
//search data when text changes in edittext
searchdata.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
list2adapter.getFilter().filter(s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
listviewforresults2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String selectedFromList2 = (String) listviewforresults2.getItemAtPosition(position).toString();
TextView textview_city_slct_to_oneway = (TextView) getActivity().findViewById(R.id.textview_city_slct_to_oneway);
textview_city_slct_to_oneway.setText(selectedFromList2);
getDialog().dismiss();
}
});
getDialog().setTitle("dialog2");
return rootView2;
}
public void prepareDummyData2() {
data.add("Chennai");
data.add("Mumbai");
data.add("Bangalore");
data.add("Madurai");
data.add("Coimbatore");
data.add("Newdelhi");
}
}
}
the above code is full fragment code with gialog innerclass too. im a beginner can you gys help me out of it?
and actually what i need is i have to click the from and to area in tab view fragment. after slecting it opens a dialog with search filter and listview. after clicking any list item it should diaplay in textview on parent fragment and after that i should be able wo pass the value to next fragment using put intent method.
currently im getting null value when i pass it to the next fragment.
i dont know why.
i have attached an image to get you the clear view. please check it.see here
I am trying to make Dialog that will consist 2x EditText and 1x Buttons. By clicking additional button you can add another 2x EditText and 1x Buttons. This 1x Button provide deleting this added pair. When i try to use button that should add another Views it's working properly. But button for deleting the View is working only for the first pairs. How can i do this with android:onClick, because i was trying buy it crashed.
Here is my code of Dialog class:
public class ExampleDialog extends AppCompatDialogFragment {
private EditText editTextUsername;
private EditText editTextPassword;
private ExampleDialogListener listener;
private LinearLayout parentLinearLayout;
private Context mContext;
Button dodaj,usun;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_template, null);
builder.setView(view)
.setTitle("Login")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();
listener.applyTexts(username, password);
}
});
editTextUsername = view.findViewById(R.id.edit_username);
editTextPassword = view.findViewById(R.id.edit_password);
parentLinearLayout = (LinearLayout) view.findViewById(R.id.parent_linear_layout);
dodaj = view.findViewById(R.id.add_field_button);
usun = view.findViewById(R.id.delete_button);
dodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.field, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
}
});
usun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
parentLinearLayout.removeView((View) v.getParent());
usun = v.findViewById(R.id.delete_button);
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (ExampleDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement ExampleDialogListener");
}
}
public void contexta(Context context)
{
this.mContext = context;
}
public interface ExampleDialogListener {
void applyTexts(String username, String password);
}
}
And there is the conception of Dialog box on the picture below:
Picture
This issue may be due to view reference. Check whether v.getParent() is the view you want to delete or not.
For testing you can use "removeViewAt(int index)" method. Pass an index and check whether view is deleted at index or not.
Excuse my noobness. I just don't understand how to implement it to work with my code. What I'm doing is editing a name that's in a list view. When editing the name in "EditDeleteList" and get back to the previous activity (ListView) to see the name updated within the list view, nothing happens. I have to go out of the activity completely to see the change reflected. How do I get this to update? I implement an onActivityReult() method but then get this error message "java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference" so I removed it completely. How I could get the list view to update without getting that error message?
ListView.Java
public class ListView extends AppCompatActivity {
private static final String TAG = "ListView";
DatabaseHelper mDatabaseHelper;
Button btnAdd;
private EditText editText;
private android.widget.ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
listView = (android.widget.ListView) findViewById(R.id.lv);
ArrayList<String> list = getIntent().getStringArrayListExtra("myList");
android.widget.ListView lv = (android.widget.ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
//Takes user back to the main activity
ImageView ivBack = (ImageView) findViewById(R.id.ivBackArrow);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: pressed back arrow");
Intent intent = new Intent(ListView.this, MainActivity.class);
startActivity(intent);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
addData(newEntry);
editText.setText("");
} else {
toastMessage("you must put something in the text field");
}
}
});
populateListView();
}
public void addData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Successfully inserted");
recreate();
} else {
toastMessage("Whoops, something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void populateListView() {
Log.d(TAG, "populateListView: displaying data in the listview");
//get data and append to list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//set it to the arraylist
listData.add(data.getString(1));
}
//create arraylist and set it to the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(adapter);
//set onclick listen to edit activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = adapterView.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: you clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()) {
itemID = data.getInt(0);
}
if (itemID > -1) {
Log.d(TAG, "onItemID: the ID is: " + itemID);
Intent editScreenIntent = new Intent(ListView.this, EditDeleteList.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
} else {
toastMessage("No ID found");
}
}
});
}
}
EditDeleteList.java
public class EditDeleteList extends AppCompatActivity {
private static final String TAG = "EditDeleteList";
DatabaseHelper mDatabaseHelper;
private ImageView ivDelete;
private ImageView ivApprove;
private EditText editHashtag;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_delete);
mDatabaseHelper = new DatabaseHelper(this);
editHashtag = (EditText) findViewById(R.id.editHashtag);
ivDelete = (ImageView) findViewById(R.id.ivDelete);
ivApprove = (ImageView) findViewById(R.id.ivApprove);
//get the intent extra from the ListView activity
final Intent receivedIntent = getIntent();
//get item ID passed as an extra
selectedID = receivedIntent.getIntExtra("id", -1);
//get name passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set text field to selected item text
editHashtag.setText(selectedName);
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
In the EditDeleteList.java I have an onClickListener that saves the changes and goes back to the previous activity by using finish();
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
Notify the adapter in some part of the activity lifecycle.
OnCreate() should not run when you go back (this is the reason you have to completely recreate the activity to see the list updated) so you should use OnRestart/OnStart/OnResume to notify the adapter to check for new items.
Check this image
I am trying to implement a spinner that is in a popup. When one selects an item and clicks the button it will display according to the selected item in the spinner.
String[]Company={"Cash","M-Pesa","Voucher","Credit-Card"};
Below is the popup containing the spinner
private void callPopup() {
LayoutInflater layoutInflater=(LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView=layoutInflater.inflate(R.layout.popup1,null);
//final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, true);
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
final Spinner popupSpinner=(Spinner)popupView.findViewById(R.id.spinner);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(StartWatchActivity.this,android.R.layout.simple_spinner_dropdown_item, Company);
popupSpinner.setAdapter(adapter);
Name =(EditText)popupView.findViewById(R.id.edtimageName);
Name.setText(String.valueOf(amount));
final Spinner spnLocale;
spnLocale=(Spinner)findViewById(R.id.spinner);
//int iCurrentSelection=spnLocale.getSelectedItemPosition();
// TextView txtView = (TextView)popupView.findViewById(R.id.txtView);
// txtView.setText("Total Cars Packed:\t" +amount +" Cars");
((Button) popupView.findViewById(R.id.saveBtn)).setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onClick(View v) {
spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!(spnLocale.getSelectedItem().toString().trim().equals("Company"))) {
if (spnLocale.getSelectedItem().toString().trim().equals("Cash")) {
Toast.makeText(StartWatchActivity.this, "Amount Paid :\t" + Name.getText().toString(), Toast.LENGTH_LONG).show();
} else if (spnLocale.getSelectedItem().toString().trim().equals("M-pesa")) {
Toast.makeText(StartWatchActivity.this, "Amount Paid :\t" + Name.getText().toString(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Toast.makeText(getBaseContext(), "Amount paid", Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), Name.getText().toString(), Toast.LENGTH_LONG).show();
popupWindow.dismiss();
}
});
((Button)popupView.findViewById(R.id.cancelbutton)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(saveBtn, 50,-30);
}
Don't mind the commented codes
try this code:
String name= null;
if(popupSpinner != null && popupSpinner.getSelectedItem() !=null ) {
name = (String)popupSpinner.getSelectedItem();
//get the name of current selected item..
} else {
//nothing is selected
}
Use below code to add spinner in popup and get it selected item as toast.
private void openSpinnerpopup() {
//inflate the layout
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View promptsView = li.inflate(R.layout.my_dialog_layout, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
//set the inflated layout in the dialog.
alertDialogBuilder.setView(promptsView);
// create alert dialog
alertDialog = alertDialogBuilder.create();
final Spinner mSpinner = (Spinner) promptsView
.findViewById(R.id.spinner);
// reference UI elements from my_dialog_layout in similar fashion
mSpinner.setOnItemSelectedListener(new OnSpinnerItemClicked());
// show it
alertDialog.show();
alertDialog.setCancelable(true);
}
//for spinneritemclick.
public class OnSpinnerItemClicked implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext(), "Selected : " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
btn.setText(parent.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
call it on buttonclick:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//open spinner as dialog
openSpinnerpopup();
}
});