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();
Related
I am using a Dialog to show a sequence of quizzes in Android. I would like to show the next quiz once the user answers True or False.
I am using a custom layout and I am controlling it with the following code:
public void showQuizDialog() {
View v;
TextView question;
// Textview showing Quiz 1 out of 3
TextView numQ;
NetworkImageView image;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
// The coordinator keeps track of the game
coordinator.setQuizStarted();
// Get the quiz using the coordinator
Quiz qX = coordinator.getQuiz();
final String answer = qX.getAnswer();
final String quizTracker = coordinator.getTracker();
// Create an instance of the dialog fragment
AlertDialog.Builder quiz = new AlertDialog.Builder(MyActivity.this);
LayoutInflater inflater = MyActivity.this.getLayoutInflater();
// Inflate and set the layout for the dialog
v = inflater.inflate(R.layout.quiz_layout,null);
// Set the question
question = (TextView) v.findViewById(R.id.content_quiz);
question.setText(qX.getQuestion());
// Set current number of question
numQ = (TextView) v.findViewById(R.id.number_quiz);
numQ.setText(quizTracker);
// Retrieves the image from url
image = (NetworkImageView) v.findViewById(R.id.thumbnail_quiz);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
String urlImage = getCompleteUrl(CODE_QUIZ_IMG);
urlImage += qX.getImg();
image.setImageUrl(urlImage, imageLoader);
quiz.setPositiveButton("True", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
if (answer.equals(quiz_true)) {
coordinator.notifyCorrectQuizNum();
Log.d(QUIZ_DIALOG,"\t\tCorrect answer! it was true");
}
coordinator.setQuizEnded(true);
coordinator.updateQuizLeft();
}
})
.setNegativeButton("False", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked to False btn
if (answer.equals(quiz_false)){
Log.d(QUIZ_DIALOG,"\t\tCorrect Answer!! It was false");
coordinator.notifyCorrectQuizNum();
}
coordinator.setQuizEnded(true);
coordinator.updateQuizLeft();
}
});
quiz.setView(v);
final AlertDialog dialog = quiz.create();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
Let's say there are 100 quizzes to show and a method of the Coordinator class that returns the number of remaining quizzes.
So, after the call
coordinator.setQuizEnded(true);
coordinator.updateQuizLeft();
the coordinator.getQuizLeft() will return 99. And coordinator.getQuiz() will point to the next quiz.
How do I update the TextView question and numQ without closing the dialog?
Try something like this :
setupQuizDialog() which is called first and creates a dialog without any content.
loadNewQuestionIntoDialog() which is continuously called to refresh the content of the dialog with a new question.
public void setupQuizDialog() {
LayoutInflater inflater = MyActivity.this.getLayoutInflater();
// Inflate and set the layout for the dialog
View v = inflater.inflate(R.layout.quiz_layout,null);
AlertDialog.Builder quiz = new AlertDialog.Builder(MyActivity.this)
.setPositiveButton("True", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Nothing, will replace later
}
})
.setNegativeButton("False", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Nothing, will replace later
}
});
quiz.setView(v);
final AlertDialog dialog = quiz.create();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
loadNewQuestionIntoDialog(dialog, 100);
}
public void loadNewQuestionIntoDialog(final AlertDialog dialog, final int questionNumber){
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
// The coordinator keeps track of the game
coordinator.setQuizStarted();
// Get the quiz using the coordinator
final String answer = qX.getAnswer();
final String quizTracker = coordinator.getTracker();
TextView question = (TextView) dialog.findViewById(R.id.content_quiz);
question.setText(qX.getQuestion());
TextView numQ = (TextView) dialog.findViewById(R.id.number_quiz);
numQ.setText(quizTracker);
// Retrieves the image from url
NetworkImageView image = (NetworkImageView) dialog.findViewById(R.id.thumbnail_quiz);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
String urlImage = getCompleteUrl(CODE_QUIZ_IMG);
urlImage += qX.getImg();
image.setImageUrl(urlImage, imageLoader);
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// User clicked OK button
if (answer.equals(quiz_true)) {
coordinator.notifyCorrectQuizNum();
Log.d(QUIZ_DIALOG,"\t\tCorrect answer! it was true");
}
coordinator.setQuizEnded(true);
if(questionNumber > 0)
loadNewQuestionIntoDialog(dialog, coordinator.updateQuizLeft());
}
});
dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// User clicked to False btn
if (answer.equals(quiz_false)){
Log.d(QUIZ_DIALOG,"\t\tCorrect Answer!! It was false");
coordinator.notifyCorrectQuizNum();
}
coordinator.setQuizEnded(true);
if(questionNumber > 0)
loadNewQuestionIntoDialog(dialog, coordinator.updateQuizLeft());
}
});
}
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();.
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
}
});
I have an Array list of xml files (xmlList) created like that :
private static ArrayList<File> xmlList = new ArrayList<File>();
public static ArrayList<File> XMLContact(File directory, File contactDirectory,
ArrayList<Contact> myContactList) {
if (!(directory.exists())) {
directory.mkdirs();}
if (!(contactDirectory.exists())) {
contactDirectory.mkdirs();
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy hh-mm-ss");
String FileName = df.format(c.getTime());
File newxmlfile = new File(Environment.getExternalStorageDirectory()+ "/newfile/contactfile/"+FileName+"xml");
xmlList.add(newxmlfile);
And then want to show the elements of this list in a pop up window (after clicking in a button: button contact ) .So I wrote this code
private void onClickButtonContact(View view) {
Button myButton = (Button) view.findViewById(R.id.buttonContact);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
xmlList = CreateContactXML.getXmlList();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
for (int i =1 ; i< xmlList.size(); i++)
{Log.e ( null, xmlList.get(i).getAbsolutePath());
final String path ;
path = xmlList.get(i).getName();
builder.setTitle("Backup Date");
builder.setItems(i, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getActivity(), "Restore done for ", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
});
}
The List is created and i can loggout its elements. But the problem is that the pop window contains only the title .
Show List in Alert as:
ArrayList<String> arrfile_path=new ArrayList<String>();
for (int i =1 ; i< xmlList.size(); i++)
arrfile_path.add(xmlList.get(i).getAbsolutePath());
builder.setTitle("Backup Date");
builder.setItems(arrfile_path, new DialogInterface.OnClickListener() {
// your code here
});
because currently you are passing only index(i) to builder.setItems