Dialog dismiss not working inside adapter - java

I have a modal(dialog) with a edit text inside and a send button, what i'm trying to do is simply send the content inside the edit text when the button is clicked, the thing is, sending the content is working, but when i call mydialog.dismiss(); it doesn't work. It is using an instance of another class to call a method retrofit, and inside the "done" and "not done" buttons i have the "enviar"(send) button which is the one i'm trying to close the modal with.
Here is the adapter code:
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent){
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(sContext).inflate(R.layout.item_tasks, parent,false);
final Tasks presenteTask = taskData.get(position);
TextView taskTitle = (TextView) listItem.findViewById(R.id.tasksTitle);
taskTitle.setText(presenteTask.getTitle());
EditText taskColor = (EditText) listItem.findViewById(R.id.taskColor);
if(presenteTask.getHexaColor().isEmpty()){
HexaColor = "#FFFFFF";
}
else{
HexaColor = presenteTask.getHexaColor();
taskColor.setBackgroundColor(Color.parseColor(HexaColor));
}
TextView taskTime = (TextView) listItem.findViewById(R.id.taskTime);
taskTime.setText(presenteTask.getTimeStart().toString().substring(0,5));
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false);
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final EditText comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
final Calendario calendario = new Calendario();
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
tasksModal.dismiss();
}
else{
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
tasksModal.dismiss();
}
}
});
tasksModal.show();
}
});
return listItem;
}
}
Thank you very much!

Firstly you have to make your dialog un-cancelable, so that outside click doesn't dismiss it using tasksModal.setCancelable(false);
Secondly no need to repeat code to create dialog inside done/undone button click. So, remove it and move it to TasksAdapter constructor.
Thirdly You are not dismissing your dialog inside done button click. So, add this tasksModal.dismiss();
Check and try with below code:
EditText comentarios;
Calendario calendario;
public TasksAdapter(#NonNull Context context, #SuppressLint("SupportAnnotationUsage") #LayoutRes ArrayList<Tasks> list){
super(context, 0, list);
sContext = context;
taskData = list;
tasksModal = new Dialog(sContext);
tasksModal.setCancelable(false); //make it un cancelable
tasksModal.setContentView(R.layout.modal_tasksdone);
tasksModal.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
comentarios = (EditText) tasksModal.findViewById(R.id.edtComentario);
calendario = new Calendario();
}
-------------------------------------------------------------
Button done = (Button) listItem.findViewById(R.id.tasksDone);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = true;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(!comentario.equals("")){
tasksModal.dismiss(); //dismiss here
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
else{
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
}
});
tasksModal.show();
}
});
Button notDone = (Button) listItem.findViewById(R.id.tasksNotDone);
notDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentarios.setText("");
yorn = false;
tarefaId = presenteTask.getTaskId();
data = presenteTask.getDataTask();
hora = String.valueOf(presenteTask.getTimeStart());
tasksModal.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comentario = comentarios.getEditableText().toString();
if(comentario.equals("")){
Toast.makeText(sContext,"Por favor digite um comentário.", Toast.LENGTH_SHORT).show();
}
else{
tasksModal.dismiss();
calendario.retrofitDoneTasks(tarefaId, comentario, data, hora, yorn, tarefaRealizadaId);
}
}
});
tasksModal.show();
}
});

Related

How Can I catch Google Play Subscriptions Payment

I try to google play subscription billing. Code is working doing payment. But I want to try when a payment successfull ı want to catch payment cost,time(montly,yearly) and I send my php API for example with an ID or Token. How can i do this.
I tried overriding onPurchasesUpdated
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
}
but it didn't work . I tried show a toast. But method didn't work.
Can I do this with this method If I can how can I run this method ?
public void openPayment(final Context mContext){
final List<String> skuList = new ArrayList<>();
//valueof1MonthMoney,valueof3MonthsMoney,valueof6MonthsMoney,valueof1YearMoney;
skuList.add("com.yeniasya.enewspaper.subscription.onemonth");
skuList.add("com.yeniasya.enewspaper.subscription.threemonth");
skuList.add("com.yeniasya.enewspaper.subscription.sixmonth");
skuList.add("com.yeniasya.enewspaper.subscription.oneyear");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext,android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View mView = li.inflate(R.layout.popup_payment, null);
ImageView imvClose=(ImageView)mView.findViewById(R.id.imvClose);
final TextView tv1MonthMoney = (TextView) mView.findViewById(R.id.tv1MonthMoney);
final TextView tv3MonthsMoney = (TextView) mView.findViewById(R.id.tv3MonthsMoney);
final TextView tv6MonthsMoney = (TextView) mView.findViewById(R.id.tv6MonthsMoney);
final TextView tv1YearMoney = (TextView) mView.findViewById(R.id.tv1YearMoney);
final TextView tvOpenPrivacy = (TextView) mView.findViewById(R.id.tvOpenPrivacy);
final LinearLayout linLay1Year = (LinearLayout) mView.findViewById(R.id.linLay1Year);
final LinearLayout linLay6Months = (LinearLayout) mView.findViewById(R.id.linLay6Months);
final LinearLayout linLay3Months = (LinearLayout) mView.findViewById(R.id.linLay3Months);
final LinearLayout linLay1Month = (LinearLayout) mView.findViewById(R.id.linLay1Month);
mBuilder.setView(mView);
dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
final SkuDetails[] s = new SkuDetails[4];
params.setSkusList(skuList).setType(BillingClient.SkuType.SUBS);
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
// Process the result.
s[0] =skuDetailsList.get(0);
s[1] =skuDetailsList.get(1);
s[2] =skuDetailsList.get(2);
s[3] =skuDetailsList.get(3);
// Toast.makeText(mContext, "listeye girdi", Toast.LENGTH_SHORT).show();
try {
tv1MonthMoney.setText(skuDetailsList.get(0).getPrice());
tv1YearMoney.setText(skuDetailsList.get(1).getPrice());
tv6MonthsMoney.setText(skuDetailsList.get(2).getPrice());
tv3MonthsMoney.setText(skuDetailsList.get(3).getPrice());
/* if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.onemonth"));
tv1MonthMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.threemonth"));
tv3MonthsMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.sixmonth"));
tv6MonthsMoney.setText(skuDetailsList.get(i).getPrice()+"");
if(skuDetailsList.get(i).getSku().equals("com.yeniasya.enewspaper.subscription.oneyear"));
tv1YearMoney.setText(skuDetailsList.get(i).getPrice()+""); */
// Toast.makeText(mContext, skuDetailsList.get(i).getSku()+"", Toast.LENGTH_SHORT).show();
}catch (Exception e){
}
}
});
dialog.show();
imvClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
linLay1Year.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[1]);
}
});
linLay1Month.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[0]);
}
});
linLay3Months.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[3]);
}
});
linLay6Months.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takeMoney(s[2]);
}
});
tvOpenPrivacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Intent i = new Intent(Intent.ACTION_VIEW);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse(mcontext.getString(R.string.PrivacyPolicyUrl)));
mcontext.startActivity(i);}catch (Exception e){}
}
});
}
private void takeMoney(SkuDetails skuDetails){
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetails)
.build();
billingClient.launchBillingFlow(MainActivity.mActivity,flowParams);
// Toast.makeText(mContext, "bastın3", Toast.LENGTH_SHORT).show();
}
#Override
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
}

Pass Data from Dialog to new Activity

I am trying pass data from my dialog box to a new Activity. So basically what i want to do for example in my Dialog box i have Name: John, when i click on my okay button it opens a new activity but i want that John to be set in my edit box on my new activity:
Here is my Activity where my Dialog box code is:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/** To change selected state view */
view.setSelected(true);
HashMap<String, Object> obj = (HashMap<String, Object>) ADAhere.getItem(position);
String SlectedName = (String) obj.get("NAME");
String SlectedPrice = (String) obj.get("PRICE");
String SlectedSize = (String) obj.get("SIZE");
String SlectedRange = (String) obj.get("RANGE");
String SlectedSupp = (String) obj.get("SUPPLIER");
// Toast.makeText(getActivity().getApplicationContext(), SlectedName, Toast.LENGTH_SHORT).show();
final Dialog dialog = new Dialog(getActivity());
dialog.getWindow();
//dialog.setTitle("Confirm your Vote");
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.diaglog);
final TextView VName = (TextView) dialog.findViewById(R.id.Name);
final TextView VRange = (TextView) dialog.findViewById(R.id.Range);
final TextView VSUPPLIER = (TextView) dialog.findViewById(R.id.Supplier);
final TextView VSIZE = (TextView) dialog.findViewById(R.id.Size);
final TextView VPrice = (TextView) dialog.findViewById(R.id.Price);
VName.setText(SlectedName);
VRange.setText(SlectedRange);
VSUPPLIER.setText(SlectedSupp);
VSIZE.setText(SlectedSize);
VPrice.setText(SlectedPrice);
dialog.show();
Button cancelBtn = (Button) dialog.findViewById(R.id.cancel_btn);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
Button UpdateBtn = (Button) dialog.findViewById(R.id.btn_update);
UpdateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
startActivity(i);
}
});
Button deleteBtn = (Button) dialog.findViewById(R.id.btn_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
startActivity(i);
}
});
dialog.show();
}
});
so i want to pass VName.setText(SlectedName); to a new activity:
name1.setText(dialogactivityname);
Pass in as an extra:
instead of:
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
startActivity(i);
you should pass in the name
Intent i = new Intent(getActivity().getApplicationContext(),Upvalence.class);
i.putExtra("string", SlectedName);
startActivity(i);
Then, on your Upvalence activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
Bundle arguments = this.getIntent().getExtras();
String yourString = arguments.getString("string");
}

Use spinner as Validation to next Activity

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

android.widget.Button cannot be cast to android.widget.CheckBox

I'm getting the error from the title in my Android project. I have searched for similar issues, which had me checkboxes casting, which seems ok, and also to clean and rebuild the project, which it did not work.
The app is crashing when I click the "Register" Button after a register form that contains EditTexts (for username, email and password) and Checkboxes for the user to pick multiple items. What should I do next?
public class RegisterActivity extends Activity {
ArrayList<Sport> sports = new ArrayList<>();
ArrayList<Sport> selectedSports = new ArrayList<>();
private void initializeSports(){
String[] sportsArray = getResources().getStringArray(array.sportsName);
for (int i = 0; i < sportsArray.length; i++){
sports.add(new Sport(i + 1, sportsArray[i]));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_register);
initializeSports();
final EditText etEmail = (EditText) findViewById(id.etEmail);
final EditText etUsername = (EditText) findViewById(id.etUsername);
final EditText etPassword = (EditText) findViewById(id.etPassword);
final Button bRegister = (Button) findViewById(id.bRegister);
final CheckBox cbSoccer = (CheckBox) findViewById(id.cbSoccer);
cbSoccer.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbFootball = (CheckBox) findViewById(id.cbFootball);
cbFootball.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbBasket = (CheckBox) findViewById(id.cbBasket);
cbBasket.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbTennis = (CheckBox) findViewById(id.cbTennis);
cbTennis.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbSwimming = (CheckBox) findViewById(id.cbSwimming);
cbSwimming.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbGym = (CheckBox) findViewById(id.cbGym);
cbGym.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbOther = (CheckBox) findViewById(id.cbOther);
cbOther.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String email = etEmail.getText().toString();
final String passcode = etPassword.getText().toString();
selectItem(v);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, email, passcode, selectedSports, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
public void selectItem(View v){
boolean checked = ((CheckBox)v).isChecked();
switch(v.getId()){
case R.id.cbSoccer:
if(checked){
selectedSports.add(sports.get(0));
} else{
selectedSports.remove(sports.get(0));
} break;
case R.id.cbFootball:
if(checked){
selectedSports.add(sports.get(1));
} else{
selectedSports.remove(sports.get(1));
} break;
case R.id.cbTennis:
if(checked){
selectedSports.add(sports.get(2));
} else{
selectedSports.remove(sports.get(2));
} break;
case R.id.cbSwimming:
if(checked){
selectedSports.add(sports.get(3));
} else{
selectedSports.remove(sports.get(3));
} break;
case R.id.cbGym:
if(checked){
selectedSports.add(sports.get(4));
} else{
selectedSports.remove(sports.get(4));
} break;
case R.id.cbBasket:
if(checked){
selectedSports.add(sports.get(5));
} else{
selectedSports.remove(sports.get(5));
} break;
case R.id.cbOther:
if(checked){
selectedSports.add(sports.get(6));
} else{
selectedSports.remove(sports.get(6));
} break;
}
}
}
You are casting the view to CheckBox in your selectItem(v) method and in your listener
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectItem(v);
}
});
You are passing the View v, i.e, the clicked button, so the button can not be casted to CheckBox.
Remove this line from listener
selectItem(v);
and it will be alright.
In the selectItem(v) method the view passed to the method is an instance of Button since it is written in the onClickListener of button
If you want to do the same first make a check in selectItem(View v) method
if(v instanceof CheckBox) {
boolean checked = ((CheckBox)v).isChecked();
}
Then proceed with the rest of code

How to pass same value to two fragment using single interface

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?

Categories