I have developed a show dialog alert box in a fragment. After pressing the OK button in the box, It does not exits the screen. The show dialog alert keeps prompting on the screen. I don't want to quit the app after pressing OK, but I want it to go back to the HomeScreen. How to make sure that show dialog alert box will exit the screen after pressing OK?
Here is the code
public class FavouriteListFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
private SharedPreference sharedPreference;
private StaggeredGridView mStaggeredView;
TextView tv;
ImageView iv;
String text;
String favouriteUrl;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_favourite_staggeredgridview, container, false);
mStaggeredView = (StaggeredGridView) rootView.findViewById(R.id.staggeredview);
mStaggeredView.setOnScrollListener(scrollListener);
sharedPreference = new SharedPreference();
// iv=(ImageView)rootView.findViewById(R.id.imageView);
text = sharedPreference.getValue(getActivity());
sharedPreference.saveFavourite(getActivity(), text);
String[] photoUrl;
photoUrl = new String[10];
if(photoUrl==null){
Toast.makeText(getActivity(),"no favourite list",Toast.LENGTH_SHORT).show();
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (photoUrl.length == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
}
for (int index = 0; index < photoUrl.length; index++) {
photoUrl[index]=text;
if(text==null){
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
else {
StaggeredGridViewItem item;
item = new FavouriteGridItem(getActivity(), photoUrl); //pass one image of index
mStaggeredView.addItem(item);
}
}
// URL url = null;
// try {
// url = new URL(text);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// Bitmap bmp = null;
// try {
// bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
// } catch (IOException e) {
// e.printStackTrace();
// }
// iv.setImageBitmap(bmp);
return rootView;
}
private void showAlert(String string, String message) {
if (getActivity() != null && !getActivity().isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.create();
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//getActivity().finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
private StaggeredGridView.OnScrollListener scrollListener = new StaggeredGridView.OnScrollListener() {
public void onTop() {
}
public void onScroll() {
}
public void onBottom() {
}
};
#Override
public void onResume() {
super.onResume();
}
}
Related
In my project. I am using two Alert Dialog Box.The two alert dialogue box used in private methods. Private methods are checkIn( ) and checkOut( )
In Main Activity, I am having One Button. Two functions for the Button. One Function is Check-In and another Function is Check out.
When I went to the Activity the Button Visible in Check-in. If I click the Button. It changes into Check out and Displays the Alert Dialogue checkIn( ) private method.
If I refresh the Activity It will change into check-in.
what is my question how to get the Checkout Action when I refresh the activity.Can anyone Solve and give solution for this...
Thank you in advance. I attached the sample code below
public class Insert_DataSql extends AppCompatActivity {
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
LocationRequest locationRequest;
LocationManager locationManager;
PreparedStatement preparedStatement;
String formattedDate;
WebConnection connectionClass;
Button cin,cout;
TextView dat,tim,adddre;
Boolean flag=true;
SharedPreferences sharedPreferences;
String username;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insertdata);
connectionClass = new WebConnection();
sharedPreferences=getSharedPreferences("LoginPref", Context.MODE_PRIVATE);//here we go getdata
user name=sharedPreferences.getString("User name",null);
//Button Click able
cin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if (flag) {
getMyCurrentLocation();
CheckinButton();
flag =false;
Toast.makeText(Insert_DataSql.this, "True statement", Toast.LENGTH_SHORT).show();
dat.setText(date);
new Insert_data().execute("");//insert for button
// tim.setText(formattedDate);
}
else{
flag =true;
getMyCurrentLocation();
CheckoutButton();
Toast.makeText(Insert_DataSql.this, "Wrong statement", Toast.LENGTH_SHORT).show();
dat.setText(date);
new Insert_data().execute("");
// tim.setText(formattedDate);
}
}
}
//Private methods for the Alert Dialogue box
private void CheckoutButton() {
if(flag == false ){
cin .setText("Check Out Sucessfull");
AlertDialog alertDialog = new AlertDialog.Builder(
Insert_DataSql.this).create();
alertDialog.setTitle("Check Out Sucessfully");
alertDialog.setMessage(adddre.getText());
alertDialog.setIcon(R.drawable.ic_access_time_black_24dp);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
}
private void CheckinButton() {
if(flag == true ){
cin.setText("Check Out");
AlertDialog alertDialog = new AlertDialog.Builder(
Insert_DataSql.this).create();
alertDialog.setTitle("Check In Sucessfully");
alertDialog.setMessage("Have A Nice Day");
alertDialog.setIcon(R.drawable.ic_access_time_black_24dp);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
}
Try something like this :
define those variables:
public static final String PREF_FLAG = "FLAG";
private static String COUT = "cout";
private static String CIN = "cin";
private static String defaultFlagValue = COUT;
and add those methods :
private String getFlag() {
return sharedPreferences.getString(PREF_FLAG, defaultFlagValue);
}
private void setFlag(String flag) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PREF_FLAG, flag);
editor.apply();
}
and update your code :
private void CheckinButton() {
if (getFlag() == COUT) {
...
setFlag(CIN);
}
}
private void CheckoutButton() {
if (getFlag() == CIN) {
...
setFlag(COUT);
}
}
and finally update tour onClick function
cin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if (getFlag() == CIN) {
getMyCurrentLocation();
CheckinButton();
Toast.makeText(Insert_DataSql.this, "True statement", Toast.LENGTH_SHORT).show();
dat.setText(date);
new Insert_data().execute("");//insert for button
// tim.setText(formattedDate);
}
else{
getMyCurrentLocation();
CheckoutButton();
Toast.makeText(Insert_DataSql.this, "Wrong statement", Toast.LENGTH_SHORT).show();
dat.setText(date);
new Insert_data().execute("");
// tim.setText(formattedDate);
}
}
}
}
Hope it will help
I have an activity with multiple EditText, after entered data and click button SAVE for save them in Database(Mysql) it open Fragment which have ListView populated with this data from database.
PROBLEM:
ListView isn't showing new data that I have entered in activity!!!, even the new data is added im my ArrayList correctly.
But when I start this Fragment for the second time it shows the Listview with new data correctly.
My Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_liste_symbole_monetaire, container, false);
symbolMonList.clear();
lv = (SwipeMenuListView) rootView.findViewById(R.id.lv_liste_symboleMon);
adapter = new SymbMoneLvAdapter(getActivity());
FloatingActionButton btn = (FloatingActionButton) rootView.findViewById(R.id.btnAjoutAjoutSymboleMon);
btn.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(), AjouterSymbMoneActivity.class);
startActivity(intent);
}
});
deleteItemLv();
getListSymbolMon();
return rootView;
}
public void deleteItemLv(){
SwipeMenuCreator creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.GRAY));
// set item width
openItem.setWidth(dp2px(90));
// set item title
openItem.setTitle("Ouvrir");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getActivity());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
deleteItem.setWidth(dp2px(90));
// set a icon
deleteItem.setIcon(R.drawable.ic_delete);
// add to menu
menu.addMenuItem(deleteItem);
}
};
lv.setMenuCreator(creator);
lv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
//Ouvrir item
break;
case 1:
deleteItemDialog(position);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
}
public int dp2px(int dp) {
DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
//Dialog delete item:
public void deleteItemDialog(final int position){
Toast toast = Toast.makeText(getActivity(), "size:"+position, Toast.LENGTH_LONG);
toast.show();
Toast toat = Toast.makeText(getActivity(), "sizeTotal:"+symbolMonList.size(), Toast.LENGTH_LONG);
toat.show();
Toast oast = Toast.makeText(getActivity(), "code:"+symbolMonList.get(position).getCode(), Toast.LENGTH_LONG);
oast.show();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity() );
alertDialogBuilder.setTitle("Supprimer");
alertDialogBuilder.setMessage("Voulez vous supprimer ce symbole monétaire?");
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String Code = symbolMonList.get(position).getCode();
Call<Void> api =API.deleteSymboleMon("delete", Code);
api.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
if(response.isSuccessful()){
Toast toast = Toast.makeText(getActivity(), "Symbole Monétaire supprimé", Toast.LENGTH_LONG);
toast.show();
symbolMonList.remove(position);
adapter.notifyDataSetChanged();
}else {
}
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
}
}
)
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}
);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
//Get liste des SM
private void getListSymbolMon(){
final ProgressDialog mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage("Chargement en cours...");
Call<List<SymbMoneItems>> api =API.getListSymbolMon();
api.enqueue(new Callback<List<SymbMoneItems>>() {
#Override
public void onResponse(Call<List<SymbMoneItems>> call, Response<List<SymbMoneItems>> response) {
if (response.isSuccessful()){
List<SymbMoneItems> List = response.body();
addListSymbolMon(List);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}else{
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
Toast toast = Toast.makeText(getActivity(), "Erreur", Toast.LENGTH_LONG);
toast.show();
}
}
#Override
public void onFailure(Call<List<SymbMoneItems>> call, Throwable t) {
Toast toast = Toast.makeText(getActivity(), "Erreur "+t, Toast.LENGTH_LONG);
toast.show();
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
});
}
public void addListSymbolMon(List<SymbMoneItems> lem){
for (int i=0;i< lem.size();i ++){
SymbMoneItems fac = lem.get(i);
symbolMonList.add(fac);
}
adapter.addAll(symbolMonList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
in my Adapter
public void addAll(ArrayList<SymbMoneItems> result) {
this.listSymb = result;
this.notifyDataSetChanged();
}
Thanks for any help.
Setting data using "=" doesn't actually have any change on dataset for adapter.
Change your addAll() method like below:
public void addAll(ArrayList<SymbMoneItems> result) {
this.listSymb.clear();
this.listSymb.addAll(result);
this.notifyDataSetChanged();
}
I am developing one app related to call block.
I have created one
dashboard activity with "three" fragment tabs. Those are like call log
tab, block tab and settings tab. I want to check the name field
condition at settings tab if valid moving to another tab otherwise
showing alert "please enter valid name". If valid name it is going to
another tab successfully. But the name is not valid i want to show
alert dialog and stay at settings tab. But i am getting twice alert
box "please enter valid name". i have checked sites but i am unable to
get the solution, please help me thanks in advance.
My code is here:
public class SettingsFragment extends Fragment{
private TabLayout tabLayout;
private ViewPager viewPager;
private View view;
private EditText et_consumerName;
DashboardActivity activity;
private static final String TAG = "SettingsFragment";
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (DashboardActivity) context;
setHasOptionsMenu(true);
}
#Override
public void onDetach() {
super.onDetach();
activity = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.settings_fragment_new, container, false);
et_consumerName = (EditText) view.findViewById(R.id.et_consumerName);
tabLayout = (TabLayout) activity.findViewById(R.id.tab_layout);
viewPager = (ViewPager) activity.findViewById(R.id.pager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// when user click on edit text then save button enable and
// i am getting shared preference boolean value.
boolean isSettingsChanged = TCPAApplication.mPref.getBoolean(Constants.IS_SETTINGS_CHANGED, false);
if (isSettingsChanged) {
int settingsPage = 2;
String consumerNam = et_consumerName.getText().toString().trim();
if (BuildConfig.DEBUGLINES) Log.e(TAG, "counsumer name is " + consumerNam);
if (!isConsumerNameValid(consumerNam)) {
viewPager.setCurrentItem(2);
enterFullNameAlert(getString(R.string.please_enter_firstname_and_lastname));
TabLayout.Tab tab1 = tabLayout.getTabAt(settingsPage);
tab1.select();
}
} else {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected (TabLayout.Tab tab){
}
#Override
public void onTabReselected (TabLayout.Tab tab){
}
}
});
return view;
}
private boolean isConsumerNameValid(String fName) {
if (fName.length() > 0 && fName.contains(" ")) {
return true;
}
return false;
}
}
public void enterFullNameAlert(String msg) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Settings");
alertDialog.setMessage(msg);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
viewPager.setCurrentItem(2);
}
});
try {
AlertDialog dialog = alertDialog.create();
dialog.setCancelable(false);
dialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
"take a global int for position of tab"
in onTabSelected method check
if(globalposition==systemTabPosition)
{
if(checkcondition)
{
tabOther.select();
globalPosition=position;
}
else
enterFullNameAlert();
}
I solved alert dialog twice problem. Thanks for giving response all.
I have taken two global variables and done the below process.
private Boolean dialogShownOnceFullName = false;
private Dialog mdialog;
private int settingsPage = 2;
public void enterFullNameAndDisplayNameAlert(String msg) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Settings");
alertDialog.setMessage(msg);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
viewPager.setCurrentItem(settingsPage);
}
});
try {
mdialog = alertDialog.create();
if (!mdialog.isShowing() && !dialogShownOnceFullName) {
mdialog.show();
dialogShownOnceFullName = true;
}
mdialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
dialogShownOnceFullName = false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Hey every one has i am create rename application in android ,I will set a Edit-text box in set error message using without toast using Alert Dialog box
Sample Code :
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.rename_title);
folderManager = new FolderManager(getActivity());
folderManager.open();
Cursor c = folderManager.queryAll(itemPos);
if (c.moveToFirst()) {
do {
Newnamefolder = c.getString(1);
} while (c.moveToNext());
}
// Set an EditText view to get user input
final EditText input = new EditText(getActivity());
input.setText(Newnamefolder);
alert.setView(input);
alert.setPositiveButton(R.string.rename_position_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Newnamefolder = input.getText().toString();
String Mesage_one = getResources().getString(R.string.folder_already_exit);
String Mesage_two = getResources().getString(R.string.types_minimum_eight_charcter);
String Mesage_three = getResources().getString(R.string.folder_empty);
String Matchnamerename = folderManager.getmatchfoldername(Newnamefolder);
if(Newnamefolder.equals(Matchnamerename))
{
input.setError(Mesage_one);
}
else if(Newnamefolder.length()>12)
{
input.setError(Mesage_two);
}
else if(Newnamefolder.equals(""))
{
input.setError(Mesage_three);
}
else
{
int newfolder = folderManager.update(itemPos,Newnamefolder);
reload();
}
}
});
alert.show();
But the problem once in click the OK button Don't show error message to exit the Alert Dialog box...
give me any solution ... Friends ?
You can extend Dialog and create your own dialog
public class CustomDialog extends Dialog implements View.OnClickListener {
private boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_dialog);
Button positive = (Button) findViewById(R.id.button_positive);
Button negative = (Button) findViewById(R.id.button_negative);
EditText field = (EditText) findViewById(R.id.field);
positive.setOnClickListener(this);
negative.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button_positive:
onPositiveButtonClicked();
break;
case R.id.button_negative:
//onNegativeButtonClicked();
break;
}
}
private void onPositiveButtonClicked() {
if(verifyForm()) {
success = true;
dismiss();
}
}
public boolean isSuccess() {
return success;
}
private boolean verifyForm() {
boolean valid = true;
/* verify each field and setError() if not valid */
if(!TextUtils.isEmpty(field.getText())) { //or any other condition
valid = false;
field.setError("error message");
}
return valid;
}
}
You can show your CustomDialog like this
final CustomDialog customDialog = new CustomDialog();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(customDialog.isSuccess()) {
//update your folder manager
}
}
}
customDialog.show();
i've recently started developing in android and am currently stuck at a point i need to receive values from a dialog box. I have a mainActivity which extends fragmentActivity and an AlertDialog Class.
1)i created a static method showDefalutDialog in AlertDialog class and its being called from mainActivity button click listener with parameters being passed to alertDialog.
2)In showDefalutDialog static method i created .setPositivebutton and .setNegativeButton with a Yes/No DialogInterface respectively.
now here's what i want to do.
1)When yes button on interface is clicked it should return a value to mainActivity
so i can implement it in an if statement to perform a certain function.
moving from windows c# programming doing so isn't a problem but i just don't know how to implement that in android below is relevant code snip
private void sendSms()
{
SharedPreferences pref = getApplicationContext().getSharedPreferences("Sms_MyPref", 0);
mail = pref.getString("email", null); // getting String
tel = pref.getString("receiver_tel", null); // getting String
layout = (LinearLayout)findViewById(R.id.linearLayout1);
from_dateEdit = (EditText) findViewById(R.id.date_edit);
to_dateEdit = (EditText) findViewById(R.id.date_edit_to);
snButton = (Button)findViewById(R.id.form_send_button);
from = (Button)findViewById(R.id.from);
to = (Button)findViewById(R.id.to);
spn = (Spinner)findViewById(R.id.form_spinner);
spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
spinnerV = (String) item;
if(pos == 0)
{
layout.setVisibility( pos == 0 ? View.VISIBLE : View.VISIBLE);
from_dateEdit.setText(DatePickerFragment.getYesteesDate());
from.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePicker();
}
});
to_dateEdit.setText(DatePickerFragment.getTodaysDate());
to.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePicker2();
}
});
new1 = null;
new2 = null;
from_dateEdit.setText(new1);
to_dateEdit.setText(new2);
}
else if(pos == 1)
{
layout.setVisibility( pos == 1 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
else if(pos == 2)
{
layout.setVisibility( pos == 2 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
else if(pos == 3)
{
layout.setVisibility( pos == 3 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
snButton.setOnClickListener(new OnClickListener() {
public void onClick(View view)
{
if(new1 == null && new2 == null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date range", false);
}
else if(new1 != null && new2 == null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date TO", false);
}
else if(new1 == null && new2 != null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date FROM", false);
}
else
{
gen = new1.toString()+","+new2.toString();
alert();
//i want to return a value from dialog yes/no click
if(/*dialog yes is clicked*/)
{
sms();
}
else if(/*dialog No is clicked*/)
{
return;
}
}
}
});
}
private void alert()
{
AlertDialogManager.showDefalutDialog(getApplicationContext(), spinnerV, mail, new1,new2);
}
public void sms()
{
String both = "{"+ spinnerV.toString() + ","+gen.toString()+","+ mail.toString()+"}";
sendSMS(tel,both);
}
and showDefaultDialog static method from AlertDialog class
#SuppressLint("InflateParams")
public static void showDefalutDialog(final Context context, String order, final String mail, String fromD, String toD) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle(R.string.finalmsg);
LayoutInflater li = LayoutInflater.from(context);
View view = li.inflate(R.layout.data_summary_view, null);
EditText EMAIL = (EditText)view.findViewById(R.id.Email);
EditText Selectedorder = (EditText)view.findViewById(R.id.order);
EditText Dfrom = (EditText)view.findViewById(R.id.edit_from);
EditText Dto= (EditText)view.findViewById(R.id.edit_to);
LinearLayout ll = (LinearLayout) view.findViewById(R.id.datelayout);
LinearLayout l2 = (LinearLayout) view.findViewById(R.id.datelayout2);
Selectedorder.setText(order);
EMAIL.setText(mail);
if(fromD.toString() != "a" && toD.toString() != "b")
{
ll.setVisibility(View.VISIBLE);
l2.setVisibility(View.VISIBLE);
Dfrom.setText(fromD);
Dto.setText(toD);
}
else if(fromD.toString() == "a" && toD.toString() == "b")
{
ll.setVisibility(View.GONE);
l2.setVisibility(View.GONE);
}
// set dialog message
alertDialogBuilder.setView(view);
//int msdt = data.toString().toCharArray().length;
//Toast.makeText(context, "MsData char count : " + msdt , Toast.LENGTH_SHORT).show();;
alertDialogBuilder
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
try {
Intent main = new Intent(context, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(main);
} catch (Exception e) {
Log.d(TAG, "Error while starting Main activity from Dialog ! ");
}
}
})
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(context,"Your Order will be sent to "+ mail +" please check your inbox for comfirmation." , Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.dismiss();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
You can define you custom interface simmilar to this one:
public interface MyDialogClickListener {
void onPositiveClicked(String value);
}
Then you create instance and pass to method, where you create dialog:
public static void showDeafultDialog(..., MyDialogClickListener listener) {
// ...
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
listener.onPositiveClicked("you can pass yout value here")
}
})
// ...
}
Handle result:
private void sendSms() {
AlertDialogManager.showDeafultDialog(..., new MyDialogClickListener() {
#Override
public void onPositiveClicked(String value) {
// do whatever you want with value
}
});