Android quick alarm - android

I have a little problem with taking a quick alarm.
The alarm works fine if I set the alarm time before normal "quick alarm". How do I set the alarm for example 8:00 pm, quick alarm for 7:55 pm this works differently does not turn on
private void showQuickAlarmDialog() {
View layout = mFactory.inflate(R.layout.quick_alarm_dialog, null);
final TextView text1 = (TextView) layout
.findViewById(android.R.id.text1);
final SeekBar slider = (SeekBar) layout
.findViewById(android.R.id.input);
int last_snooze = mPrefs.getInt(PREF_LAST_QUICK_ALARM, 0);
slider.setMax(59);
slider.setProgress(last_snooze);
text1.setText(AlarmClock.this.getString(R.string.minutes,
String.valueOf(last_snooze + 1)));
slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seek, int value,
boolean fromTouch) {
text1.setText(AlarmClock.this.getString(R.string.minutes,
String.valueOf(value + 1)));
}
public void onStartTrackingTouch(SeekBar seek) {
}
public void onStopTrackingTouch(SeekBar seek) {
}
});
AlertDialog d = new AlertDialog.Builder(this)
.setTitle(R.string.quick_alarm)
.setView(layout)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
int snooze_min = slider.getProgress() + 1;
long snoozeTarget = System.currentTimeMillis()+ 1000 * 60 * snooze_min;
Alarms.calculateNextAlert(AlarmClock.this).getAlert();
//if (nextAlarm > snoozeTarget) {
//alarm will fire before snooze will...
//}
//else {
Alarms.saveSnoozeAlert(
AlarmClock.this,0,snoozeTarget,AlarmClock.this.getString(R.string.quick_alarm));
Alarms.setNextAlert(AlarmClock.this);
Toast.makeText(
AlarmClock.this,
getString(
R.string.alarm_alert_snooze_set,
snooze_min),
Toast.LENGTH_LONG).show();
updateSnoozeVisibility();
mPrefs.edit()
.putInt(PREF_LAST_QUICK_ALARM,
snooze_min - 1).commit();
// }
}
}).show();
}
private void updateSnoozeVisibility() {
long next_snooze = mPrefs.getLong(Alarms.PREF_SNOOZE_TIME, 0);
View v = (View) findViewById(R.id.snooze_message);
if (next_snooze != 0) {
TextView tv = (TextView) v.findViewById(R.id.snooze_message_text);
Calendar c = new GregorianCalendar();
c.setTimeInMillis(next_snooze);
String snooze_time = Alarms.formatTime(AlarmClock.this, c);
tv.setText(getString(R.string.snooze_message_text, snooze_time));
v.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.GONE);
Alarms.disableSnoozeAlert(AlarmClock.this);
Toast.makeText(AlarmClock.this,
getString(R.string.snooze_dismissed),
Toast.LENGTH_LONG).show();
Alarms.setNextAlert(AlarmClock.this);
}
});
v.setVisibility(View.VISIBLE);
} else {
v.setVisibility(View.GONE);
}
}
private void updateEmptyVisibility() {
View v = findViewById(R.id.alarms_list_empty);
if (v != null)
v.setVisibility(mAlarmsList.getAdapter().getCount() < 1 ? View.VISIBLE
: View.GONE);
}
In one sentence. I can't turn on quick alarm if the normal alarm is set at a later time.

Related

Customizing my alertbox using inflater doesn't work

I am a beginner to Android Studio. I am working on my android quiz application for our school activity. The code shown below is what i have to check if my answer in my true or false question is correct. I want to display a custom AlertBox, but it doesn't work.The app stops and goes back its previous activity. I tried to change it to the default alertbox. It works fine, but if I add inflater it doesn't work. What is wrong with my code?
public void checkAnswer(View view) {
// Get pushed button.
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
TextView title = (TextView) view.findViewById(R.id.title);
ImageButton imageButton = (ImageButton)
view.findViewById(R.id.image);
TextView laman = (TextView) view.findViewById(R.id.laman);
if (btnText.equals(rightAnswer)) {
// Correct!
startService(new Intent(roxasquiz.this, tamamusic.class));
imageButton.setImageResource(R.drawable.check);
title.setText("Magaling!");
laman.setText("Tama ang iyong sagot! ");
rightAnswerCount++;
} else {
// Wrong...
startService(new Intent(roxasquiz.this, malimusic.class));
title.setText("Magsanay pa!");
laman.setText("Mali ang iyong sagot! ");
imageButton.setImageResource(R.drawable.wrong);
}
// Create Dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View v = inflater.inflate(R.layout.custom_layout, (ViewGroup) view, false);
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT) {
// Show Result.
Intent intent = new Intent(getApplicationContext(), roxasresult.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();
}
}
});
builder.setView(v);
builder.setCancelable(false);
builder.show();
}
Here is the code that is written before the codes above.
public class roxasquiz extends AppCompatActivity {
private TextView timer;
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1;
private Button answerBtn2;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 3;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
// {"Question", "Right Answer", "Choice1", "Choice2", "Choice3"}
{"Sa loob ng 10 taon naging speaker of the House si Manuel Roxas. ",
"MALI", "TAMA", },
{"Nagtapos ng abogasya si Manuel Roxas sa University of Santo
Tomas.", "MALI", "TAMA",},
{"Sa lalawigan ng Tarlac ipinanganak si Manuel Roxas. ", "MALI",
"TAMA", },
};
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.rizaltruefalse);
stopService(new Intent(roxasquiz.this, BackgroundSoundService.class));
countLabel = (TextView)findViewById(R.id.countLabel);
questionLabel = (TextView)findViewById(R.id.questionLabel);
answerBtn1 = (Button)findViewById(R.id.answerBtn1);
answerBtn2 = (Button)findViewById(R.id.answerBtn2);
timer = (TextView)findViewById(R.id.timerlabel);
timer = (TextView)findViewById(R.id.timerlabel);
startService(new Intent(roxasquiz.this, timer.class));
new CountDownTimer(61000, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Oras:" + millisUntilFinished / 1000);
}
public void onFinish() {
timer.setText("TAPOS NA!");
timeUp();
}
private void timeUp() {
stopService(new Intent(roxasquiz.this, tamamusic.class));
stopService(new Intent(roxasquiz.this, malimusic.class));
AlertDialog.Builder builder = new AlertDialog.Builder(
roxasquiz.this);
builder.setTitle("Tapos na ang oras!")
.setCancelable(false)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent intent = new
Intent(getApplicationContext(), roxasresult.class);
intent.putExtra("RIGHT_ANSWER_COUNT",
rightAnswerCount);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}.start();
// Create quizArray from quizData.
for (int i = 0; i < quizData.length; i++) {
// Prepare array.
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]); // Country
tmpArray.add(quizData[i][1]); // Right Answer
tmpArray.add(quizData[i][2]); // Choice1
// Add tmpArray to quizArray.
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
// Update quizCountLabel.
countLabel.setText("Tanong " + quizCount);
// Generate random number between 0 and 14 (quizArray's size - 1).
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
// Pick one quiz set.
ArrayList<String> quiz = quizArray.get(randomNum);
// Set question and right answer.
// Array format: {"Country", "Right Answer", "Choice1", "Choice2",
"Choice3"}
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
// Remove "Country" from quiz and Shuffle choices.
quiz.remove(0);
answerBtn1.setText("TAMA");
answerBtn2.setText("MALI");
quizArray.remove(randomNum);
}
This is my code to make it a default alertbox and it works fine.
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
String laman;
if (btnText.equals(rightAnswer)) {
// Correct!
startService(new Intent(roxasquiz.this, tamamusic.class));
alertTitle = "Magaling!";
laman = "Tama ang iyong sagot";
rightAnswerCount++;
} else {
// Wrong...
alertTitle = "Magsanay pa!";
laman = "Mali ang iyong sagot";
}
// Create Dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage(laman);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT) {
// Show Result.
Intent intent = new Intent(getApplicationContext(), roxasresult.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Can't stop CountDownTimer

Good day! I try to make countdown timer till date, but I have next problem: when I set date and time - it's work's fine, but when I try to reset timer and then reload application I still saw the previous timer countdown. I have already try everything that I can even imaging.
public class MainActivity extends AppCompatActivity {
TextView tv_days;
TextView tv_hours;
TextView tv_minutes;
TextView tv_seconds;
TextView tv_msg;
ImageButton btnTimer;
ImageButton btnExit;
long total_millisec;
CountDownTimer cdt;
TimerPreference timerPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_days = (TextView) findViewById(R.id.days);
tv_hours = (TextView) findViewById(R.id.hours);
tv_minutes = (TextView) findViewById(R.id.minutes);
tv_seconds = (TextView) findViewById(R.id.seconds);
tv_msg = (TextView) findViewById(R.id.msg);
btnTimer = (ImageButton) findViewById(R.id.setTimer);
btnExit = (ImageButton) findViewById(R.id.resetTimer);
final Intent setTimer = new Intent(this, ShowActivity.class);
timerPreference = new TimerPreference(this);
total_millisec = timerPreference.getTime();
if(total_millisec != 0){
setTime();
}
View.OnClickListener mainWin = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.setTimer:
startActivity(setTimer);
break;
case R.id.resetTimer:
resetTimer();
break;
}
}
};
btnTimer.setOnClickListener(mainWin);
btnExit.setOnClickListener(mainWin);
}
public void setTime() {
cdt = new CountDownTimer(total_millisec, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timerPreference.setTime(millisUntilFinished);
long days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
millisUntilFinished -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished);
millisUntilFinished -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished);
millisUntilFinished -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);
setScreenData(String.valueOf(days),
String.valueOf(hours),
String.valueOf(minutes),
String.valueOf(seconds));
}
#Override
public void onFinish() {
Log.e("TIMER:"," FINISH!");
}
};
cdt.start();
}
public void setScreenData(String setD, String setH,String setM, String setS){
tv_days.setText(setD);
tv_hours.setText(setH);
tv_minutes.setText(setM);
tv_seconds.setText(setS);
tv_msg.setText("");
}
private void resetTimer(){
AlertDialog.Builder quitDialog = new AlertDialog.Builder(this);
quitDialog.setTitle("Reset Timer?");
quitDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
quitDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
cancelTimer();
recreate();
}
});
quitDialog.show();
}
void cancelTimer() {
if(cdt!=null) {
cdt.cancel();
}
timerPreference.clearPreferences();
}
}
I logged this code for some hours, and I have noticed that even after I cancel timer, clear preferences and reload app, "total_millisec = timerPreference.getTime();" in onCreate still have time information...
Thank you in advance, for any answer.
UDP:
TimerPreference.java
class TimerPreference {
private SharedPreferences prefs;
TimerPreference(Context context){
prefs = context.getSharedPreferences("Timer",Context.MODE_PRIVATE);
}
void setTime(Long time){
prefs.edit().putLong("time", time).apply();
}
Long getTime(){
return prefs.getLong("time", 0);
}
void clearPreferences(){
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
}
}
UPD2:
I logged code using String.valueOf(timerPreference.getTime()) and get that when I press reset I get "TIME-IN-cancelTimer: 0", than activity reloaded by onrecreate(); and I get "TIME-IN-onCreate: 0", but when I close app and open again - I get "TIME-IN-onCreate: 47025952", so now I almoust sure that the problem is in class TimerPreference...but I still can't find solution.
After hours I have noticed another pattern: if to set time, reset the timer and restart the application - everything works as it should. But if to set the time, restart it, and then reset the timer - after next app start, it again start countdown.
Add timerPreference.setTime(0); after timerPreference.clearPreferences(); in cancelTimer() method.
Try to use editor.commit(); in clearPreferences() method of TimerPreference class

How to start one alert dialog box after another in android?

What I'm trying to do is, I have started an alert dialog box from my main activity. The user has to solve basic math and click the positive button. If he is successful, i want that the same alert dialog box be displayed again. Basically I want the user to successfully solve math 3 times (display same alert dialog box 3 times). The code below throws exception at commented line:
IllegalStateException:
The specified child already has a parent. You must call removeView() on the child's parent first.
How can I resolve this?
public class SolveMath extends DialogFragment {
MyDialog myDialog;
int count = 0;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
myDialog = (MyDialog) activity;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_layout, null);
final ComponentName component = new ComponentName(view.getContext(), BlockOutgoingCall.class);
final Globals globals = ((Globals) view.getContext().getApplicationContext());
builder.setView(view);
builder.setCancelable(false);
builder.setTitle("Solve!");
Random r = new Random();
int min = 50;
int max = 500;
final int i1 = r.nextInt(max - min + 1) + min;
final int i2 = r.nextInt(max - min + 1) + min;
TextView math = (TextView) view.findViewById(R.id.math);
String solve = i1 + "+" + i2;
math.setText(solve);
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "You're still drunk!", Toast.LENGTH_LONG).show();
globals.setGlobalVarValue("true");
}
});
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
EditText mathans = (EditText) view.findViewById(R.id.mathans);
if (mathans.getText().toString().trim().equals("")) {
mathans.setError("Field Empty!");
Toast.makeText(getActivity(), "Please Enter Value", Toast.LENGTH_LONG).show();
} else {
int abc = Integer.parseInt(mathans.getText().toString());
if (abc == (i1 + i2)) {
// globals.setGlobalIntValue(count);
if (count == 3) {
Toast.makeText(getActivity(), "You are good to go!", Toast.LENGTH_LONG).show();
globals.setGlobalVarValue("false");
view.getContext().getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
myDialog.showResult(true);
count = 0;
} else {
count++;
builder.show(); //throwing exception here
}
} else {
Toast.makeText(getActivity(), "Sorry, wrong answer, try again!", Toast.LENGTH_LONG).show();
globals.setGlobalVarValue("true");
myDialog.showResult(false);
}
}
}
});
Dialog dialog = builder.create();
return dialog;
}
public interface MyDialog {
public void showDialog();
public void showResult(boolean b);
}
}
Here may be a solution with which the dialog don't have to be started again. Firstly, make i1 and i2 as class variables of SolveMath. Then you can create a function for example generateMathProblem:
private void generateMathProblem() {
Random r = new Random();
int min = 50;
int max = 500;
i1 = r.nextInt(max - min + 1) + min;
i2 = r.nextInt(max - min + 1) + min;
TextView math = (TextView) view.findViewById(R.id.math);
String solve = i1 + "+" + i2;
math.setText(solve);
}
Finally replace builder.show(); with generateMathProblem();.

how to pass yes/no value from alertdialog to an Activity in android

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

not able to show custom Toast

I have two custom toasts.
When phone state is ringing it will show first toast, there is one button when i click on that button first toast will be dismiss and second toast will be shown.
And when I again click on second toast button it will dismiss second toast and show first toast. How can i do this? Please help me as soon as possible.
Here is my code:
hideBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(numberToast!=null){
numberToast.cancel();
showTest_Toast();
}
//------------------------------------------------------------------
public void showTest_Toast() {
LayoutInflater inflater = LayoutInflater.from(ctx);
View v = new View(ctx);
test_layout = inflater.inflate(R.layout.test_toast,
(ViewGroup) v.findViewById(R.id.test_id));
testBtn = (Button) test_layout.findViewById(R.id.test_toast_button);
testToast = new Toast(ctx);
testToast.setGravity(Gravity.LEFT, 0, 0);
testToast.setView(test_layout);
// test_layout.setVisibility(View.INVISIBLE);
if (showButton == 1) {
SharedPreferences timer_preferences = PreferenceManager
.getDefaultSharedPreferences(ctx);
String timer = timer_preferences.getString("duration", null);
new CountDownTimer(Long.parseLong(timer), 1000) {
public void onTick(long millisUntilFinished) {
testToast.show();
}
public void onFinish() {
// testToast.cancel();
}
}.start();
} else {
new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished) {
testToast.show();
}
public void onFinish() {
// testToast.cancel();
}
}.start();
}
testBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (testToast!=null) {
testToast.cancel();
numberToast.show();
}
}
});
}
Try to open Custom Popup Screen. Its easy for u.
xml
<?xml version="1.0" encoding="utf-8"?>
<item
android:id="#+id/item_movies"
android:showAsAction="ifRoom|withText"
android:title="Default Screen"
android:visible="true"
/>
<item
android:id="#+id/item_music"
android:showAsAction="ifRoom|withText"
android:title="Silent"
android:visible="true"/>
java code.
public void onWindowFocusChanged(boolean hasFocus) {
int[] location = new int[2];
Button button = (Button) myview.findViewById(R.id.slidehandlebutton);
// Get the x, y location and store it in the location[] array
button.getLocationOnScreen(location);
// Initialize the Point with x, and y positions
p = new Point();
p.x = location[0];
p.y = location[1];
}
private void showPopup(Unlock_hud unlock_hud, Point p2) {
// TODO Auto-generated method stub
int popupWidth = 180;
int popupHeight = 80;
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout1 = layoutInflater.inflate(R.layout.popup_layout, null);
// Creating the PopupWindow
// Some offset to align the popup a bit to the right, and a bit down,
// relative to button's position.
int OFFSET_X = -200;
int OFFSET_Y = 5;
// Displaying the popup at the specified location, + offsets.
params2.x =20;
params2.y = 40;
wm2.addView(layout1, params2);
isDialogShow = true;
// Getting a reference to Close button, and close the popup when
// clicked.
Button close = (Button) layout1.findViewById(R.id.stop);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
wm2.removeView(layout1);
isDialogShow = false;
onDestroy();
}
});
on Button click.
case R.id.slidehandlebutton:
if (isDialogShow) {
DissmissPopup();
} else {
showPopup(Unlock_hud.this, p);
}

Categories

Resources