My android app keeps chrashing when I change the keyboard type on my numberPicker to "TYPE_CLASS_NUMBER", when typing the first digit. The same works without specifying the keyboard type. So it seems that the keyboard change is the problem.
Here's the code:
public void chooseAmps(View view) {
final NumberPicker numberPicker = new NumberPicker(this);
NumberPicker.Formatter formatter = new PickerFormatter();
//numberPicker.setFormatter(formatter);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(100);
numberPicker.setDisplayedValues(getStringArray(0, 10));
enableNumberPickerManualEditing(numberPicker);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.AmpsMessage)
.setTitle(R.string.AmpsTitle)
.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("UI", String.valueOf(numberPicker.getValue()));
double currentDesired = numberPicker.getValue() / 10.0;
charger.setCurrentDesired(currentDesired);
Log.d("UI", String.valueOf(charger.getCurrentDesired()));
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setView(numberPicker);
AlertDialog dialog = builder.create();
dialog.show();
}
String[] getStringArray(double begin, double end) {
String[] stringArray = new String[(int) ((end - begin) * 10)+1];
double number = begin;
for (int i = 0; i < (int) ((end - begin) * 10+1); i++) {
stringArray[i] = String.format("%.1f", number);
number += 0.1;
}
Log.d("UI", String.valueOf(number));
return stringArray;
}
public static void enableNumberPickerManualEditing(NumberPicker numPicker) {
int childCount = numPicker.getChildCount();
for (int i = 0; i < childCount; i++) {
View childView = numPicker.getChildAt(i);
if (childView instanceof EditText) {
EditText editText = (EditText) childView;
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
return;
}
}
}
}
The crash message here:
"Process: com.jacobi.mario.charger, PID: 28169
java.lang.IndexOutOfBoundsException: setSpan (3 ... 3) ends beyond
length 2
at
android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1320)
at
android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:683)
at
android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:676)
at android.text.Selection.setSelection(Selection.java:78)
at android.widget.EditText.setSelection(EditText.java:96)
at
android.widget.NumberPicker$SetSelectionCommand.run(NumberPicker.java:2278)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6236)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)"
Anybody got a tip for me?
Wow I just found a solution, but maybe there is a better on?
For me it worked to change:
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
to
editText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
Related
I have 9 edittext. Each edittext is in the form of a square. I look if all edittext has values, then an alert message is displayed without click of any button.
I tried with this code but it does not run.
Any help would be appreciated.
public int Summ(int x, int y, int z) {
int sum = 0;
sum = x + y + z;
return sum;
}
private void alertDialogLost()
{
int a= Integer.parseInt(et1.getText().toString());
int b = Integer.parseInt(et2.getText().toString());
int c = Integer.parseInt(et3.getText().toString());
int d = Integer.parseInt(et4.getText().toString());
int e = Integer.parseInt(et5.getText().toString());
int f = Integer.parseInt(et6.getText().toString());
int g = Integer.parseInt(et7.getText().toString());
int h = Integer.parseInt(et8.getText().toString());
int k = Integer.parseInt(et9.getText().toString());
if ((Summ(a,b,c)== Solution)&&(Summ(d,e,f)== Solution)&&(Summ(g,h,k)==Solution)&&
(Summ(a,d,g)==Solution)&&(Summ(b,e,h)== Solution)&&(Summ(c,f,k)==Solution)
&&(Summ(a,e,k)==Solution)&&(Summ(c,e,g)==Solution))
{
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.alertdiag, null);
TextView title = (TextView) view1.findViewById(R.id.title);
TextView message = (TextView) view1.findViewById(R.id.message);
ImageView icone = (ImageView) view1.findViewById(R.id.icone);
title.setText("Result");
icone.setImageResource(R.drawable.smilega);
message.setText("you have winner");
builder1.setPositiveButton("contenue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
finish();
}
});
builder1.setView(view1);
builder1.setCancelable(false);
AlertDialog alertDialog1 = builder1.create();
alertDialog1.show();
}
}
If you just want to show an AlertDialog the moment all nine EditText fields have values in them, using a TextWatcher would probably do the trick.
First, let's start with making things easier on ourselves. We'll add each EditText to an ArrayList, so we can iterate through them with a forEach loop:
List<EditText> editTextArrayList= new ArrayList<>();;
editTextArrayList.add(et1);
editTextArrayList.add(et2);
editTextArrayList.add(et3);
editTextArrayList.add(et4);
editTextArrayList.add(et5);
editTextArrayList.add(et6);
editTextArrayList.add(et7);
editTextArrayList.add(et8);
editTextArrayList.add(et9);
Then, let's set up a method to iterate through all nine EditText fields, checking if each one has a value. If any of them do not, the AlertDialog will not show:
private void checkAllEditTexts() {
boolean allFilled = true;
for (EditText editText : editTextArrayList) {
if (editText.getText().toString().isEmpty()) {
allFilled = false;
break;
}
}
if (allFilled) {
// show your AlertDialog
}
}
Then we set up our TextWatcher, which will call the checkAllEditTexts() method if any text is changed on the EditText fields we'll be assigning it to:
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
checkAllEditTexts();
}
};
And finally, just below where we added the EditText fields to the ArrayList, we set up a forEach loop to add the TextWatcher:
List<EditText> editTextArrayList= new ArrayList<>();;
editTextArrayList.add(et1);
editTextArrayList.add(et2);
editTextArrayList.add(et3);
editTextArrayList.add(et4);
editTextArrayList.add(et5);
editTextArrayList.add(et6);
editTextArrayList.add(et7);
editTextArrayList.add(et8);
editTextArrayList.add(et9);
for (EditText editText : editTextArrayList) {
editText.addTextChangedListener(textWatcher);
}
...and that should display your AlertDialog as soon as all nine text fields have a value.
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();
I have an android application when clicked on an option from a side bar it goes to a fragment, and then into another fragment which has clickable radio buttons. When clicked on these it will create a popup window with some text fields in it.
Basically this is how the flow goes,
Activity --> Fragment 1 --> Fragment 2 --> PopupWindow
And i have a spinner on this PopupWindow, but when i click on it to select a value it throws the following exception. I don't understand why this happen.
Process: com.informaticsint.claimassistant, PID: 5045
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#945936c is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:849)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:337)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.widget.PopupWindow.invokePopup(PopupWindow.java:1329)
at android.widget.PopupWindow.showAsDropDown(PopupWindow.java:1155)
at android.widget.ListPopupWindow.show(ListPopupWindow.java:791)
at android.widget.Spinner$DropdownPopup.show(Spinner.java:1366)
at android.widget.Spinner.performClick(Spinner.java:828)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is the Spinner code that cause the problem. Which is in the below mentioned AssignmentDetailsActivity class, showDamagedItemEntryPopup() method
statusSpinner = (Spinner)popupView.findViewById(R.id.popup_status_spinner);
ArrayAdapter<String> statusSpinnerArrayAdapter = new ArrayAdapter<String>(AssignmentDetailsActivity.this, android.R.layout.simple_spinner_item, statusSpinnerArray);
statusSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerArrayAdapter);
This is my method that creates the popup which is in my AssignmentDetailsActivity class
public void showDamagedItemEntryPopup(RadioButton radioButton, View view){
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.component_selection_popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// Set popup Animation style
popupWindow.setAnimationStyle(R.style.popupAnimation);
Button buttonClose = (Button)popupView.findViewById(R.id.close_add_component_btn);
// Close button damaged item popop window
buttonClose.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
originalAmount = (EditText)popupView.findViewById(R.id.popup_add_component_original_amount);
customerContribution = (EditText)popupView.findViewById(R.id.popup_percentage);
quantity = (EditText)popupView.findViewById(R.id.popup_quantity);
finalAmount = (EditText)popupView.findViewById(R.id.popup_add_component_final_amount);
remarks = (EditText)popupView.findViewById(R.id.popup_add_component_remarks);
// Item Spinner
itemSpinnerArray = new ArrayList<String>();
itemSpinnerArray.add("Select Item");
// Status Spinner
ArrayList<String> statusSpinnerArray = new ArrayList<String>();
statusSpinnerArray.add("FDR");
statusSpinnerArray.add("DR");
statusSpinnerArray.add("SP");
damageComponenetAutoCompleteTextview = (AutoCompleteTextView) popupView.findViewById(R.id.popup_damage_component_item);
damageComponenetAutoCompleteTextview.requestFocus();
ArrayAdapter<String> itemSpinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, itemSpinnerArray);
damageComponenetAutoCompleteTextview.setThreshold(1);
damageComponenetAutoCompleteTextview.setAdapter(itemSpinnerArrayAdapter);
damageComponenetAutoCompleteTextview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
itemSpinnerValue = (String) parent.getItemAtPosition(position);
Log.d("SK-->", "----------------------------------------------------------");
Log.d("SK-->","itemSpinnerValue: " + itemSpinnerValue);
}
});
statusSpinner = (Spinner)popupView.findViewById(R.id.popup_status_spinner);
ArrayAdapter<String> statusSpinnerArrayAdapter = new ArrayAdapter<String>(AssignmentDetailsActivity.this, android.R.layout.simple_spinner_item, statusSpinnerArray);
statusSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerArrayAdapter);
//Creating a text Watcher
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
//here, after we introduced something in the EditText we get the string from it
//String answerString = originalAmount.getText().toString();
if (originalAmount.getText().toString().trim().equals("") || customerContribution.getText().toString().trim().equals("")
|| quantity.getText().toString().trim().equals("")) {
// Error , one or more editText are empty
}
else
{
calculateFinalAmount();
}
//and now we make a Toast
//modify "yourActivity.this" with your activity name .this
//Toast.makeText(yourActivity.this,"The string from EditText is: "+answerString,0).show();
}
};
// Adding Text Watcher to our text boxes
originalAmount.addTextChangedListener(textWatcher);
customerContribution.addTextChangedListener(textWatcher);
quantity.addTextChangedListener(textWatcher);
// Show the popup
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
public void onSaveItem(View view) {
statusSpinnerValue = (String) statusSpinner.getItemAtPosition(statusSpinner.getSelectedItemPosition());
statusSpinnerValue = "ABC";
itemSpinnerValue = "TEST ITEM";
originalAmount.setText("50");
customerContribution.setText("25");
quantity.setText("1");
if(itemSpinnerValue.matches("Select Item") ||itemSpinnerValue.matches("") || statusSpinnerValue.matches("") || originalAmount.getText().toString().matches("") || customerContribution.getText().toString().matches("") ||
quantity.getText().toString().matches("")){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("ERROR!");
builder.setMessage("Please Fill the Required Fields.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else{
Log.e("TEST", "Check Passed");
Date date = new Date();
if(mDbHandler.itemAlreadyExist(reportID,"item_name", itemSpinnerValue, "DamageComponent") == false){
mDbHandler.addDamageComponent(reportID, itemSpinnerValue, statusSpinnerValue, originalAmount.getText().toString(), Double.parseDouble(customerContribution.getText().toString()),
Integer.parseInt(quantity.getText().toString()), finalAmount.getText().toString(), remarks.getText().toString());
mDbHandler.updateReport(reportID, date.toString(), "time_last_modified");
Toast.makeText(this,"Component Successfully Added",Toast.LENGTH_SHORT).show();
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("ERROR!");
builder.setMessage("Item Already Exist.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
mDbHandler.close();
}
}
Spent 2 days for exactly the same problem :(
The only workaround I find is to use spinner in dialog mode
android:spinnerMode="dialog"
Glad to help you again, Have a look at this question's answers. You are showing popup too early so that you need to delay the run like this
view.post(new Runnable() {
public void run() {
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
});
UPDATE :
OR try
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
}, 1000); //Delay one second
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();.
I'm using number picker in a dialog and want to change the scroll direction from Up to down. Which mean currently by default if i scroll up, numbers come from bottoms side but i want them to come from upside and scroll will be downwards instead of upwards. Here is my number picker Dialog Code.
private static void getMeasure(int textMsg, final BoardRect item,
final int defaultValue, final int maxValue,
final OnUIMeasureReadListener listener) {
final NumberPicker picker = new NumberPicker(
AppContext.getActivityContext());
picker.setMinValue(-1);
picker.setMaxValue(maxValue);
picker.setWrapSelectorWheel(false);
picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
// create actual dialog
final AlertDialog.Builder msgbox = new AlertDialog.Builder(
AppContext.getActivityContext());
msgbox.setCancelable(true);
msgbox.setTitle(AppContext.getActivityContext().getResources()
.getString(R.string.rect_dimen));
msgbox.setMessage(textMsg);
msgbox.setView(picker);
msgbox.setPositiveButton(AppContext.getActivityContext().getResources()
.getString(R.string.dlg_positive_btn),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
listener.measureRead(picker.getValue());
} catch (Exception ex) {
}
}
});
AlertDialog dialog = msgbox.create();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();
wmlp.gravity = Gravity.BOTTOM | Gravity.RIGHT;
wmlp.x = 135; // x position
wmlp.y = 0; // y position
dialog.getWindow().setAttributes(wmlp);
dialog.show();
dialog.getWindow().setLayout(350, 650);
}
I just had the same problem. I used the setDisplayedValues() method of the NumberPicker class to explicitly set the values to be displayed. You can generate an array of strings that represent the string values of the numbers you want:
public String[] getDisplayValues(int minimumInclusive, int maximumInclusive) {
ArrayList<String> result = new ArrayList<String>();
for(int i = maximumInclusive; i >= minimumInclusive; i--) {
result.add(Integer.toString(i));
}
return result.toArray(new String[0]);
}
Store that array in a field _displayValues and then you can call:
picker.setDisplayValues(_displayValues);
//we want the max value to be the index of our last value
picker.setMaxValue(_displayValues.length - 1);
When the OnValueChangeListener event is raised, use newVal as an index into your array:
var realValue = Integer.parseInt(_displayValues[newVal]);
Hope that helps.