number picker doesn't show values - android

I'm using some number pickers from a xml-file in a alert dialog to get some coordinate inputs. The pickers are created and have some values (when you mark it and the keyboard opens you can see them), but won't show other values and the displayed value has the same color as the background.
When I press the OK-Button, the (more or less) displayed values are given correctly to the activity.
My Code:
public void showDialog()
{
final Context context=getApplicationContext();
final AlertDialog.Builder d = new AlertDialog.Builder(this);
final NumberPicker np1, np2, np3, np4, np5, np6, np7, np8;
final String abc[] = new String[] { "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z" };
final String zero_to_99[] = new String[100];
//init string array
for(int i=0; i<=99; i++)
{
zero_to_99[i] = Integer.toString(i);
if(zero_to_99[i].length() == 1)
zero_to_99[i] = "0"+Integer.toString(i);
}
LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.dialog_pick_coord,null);
String txt_title = context.getResources().getString(R.string.txt_head_search_coord);
d.setTitle(txt_title);
//Spalte
np1 = (NumberPicker) view.findViewById(R.id.p1);
np1.setMaxValue(60); // max value 60
np1.setMinValue(1); // min value 1
np1.setWrapSelectorWheel(false);
//Zeile
np2 = (NumberPicker) view.findViewById(R.id.p2);
np2.setMaxValue(25); // max value Z
np2.setMinValue(0); // min value A
np2.setDisplayedValues( abc );
np2.setWrapSelectorWheel(false);
//100km Quadrat 1
//more number pickers
//100km Quadrat 2
//more number pickers
//Easting xx*
//more number pickers
//Easting **x
//more number pickers
//Northing xx*
//more number pickers
//Northing **x
//more number pickers
np1.setValue(utmCoordElements[0]);
np2.setValue(utmCoordElements[1]);
np3.setValue(utmCoordElements[2]);
np4.setValue(utmCoordElements[3]);
np5.setValue(utmCoordElements[4]);
np6.setValue(utmCoordElements[5]);
np7.setValue(utmCoordElements[6]);
np8.setValue(utmCoordElements[7]);
d.setPositiveButton(context.getResources().getString(R.string.Accept), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Code for click on positive button
}
});
d.setNegativeButton(context.getResources().getString(R.string.Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Code for click on negative button
}
});
d.setView(view);
d.show();
}
In my "main activity" I have a Button with a onClickListeners wich calls the showDialog() Method

Related

ListView with CHOICE_MODE_SINGLE. Select up to one choice

I have a multi choice list inside an AlertDialog.
Reading the documentation of CHOICE_MODE_SINGLE, I thought that you could have one or no item checked but for me it behaves like a Radio Button List. It starts with all checkboxes unchecked by default by once I check one, it cannot be unchecked.
I tried hacking it with manual setItemChecked inside onClick but that is not a solution.
What am I doing wrong? How to achieve one or no checkbox in a ListView?
Here's my code:
builder.setMultiChoiceItems(titles, new boolean[titles.length], new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean b) {
if (selectedId == -1) {
selectedId = position;
} else {
if (selectedId == position) {
mDialog.getListView().setItemChecked(position, false);
selectedId = -1;
} else {
mDialog.getListView().setItemChecked(selectedId, false);
selectedId = position;
}
}
}
});
mDialog = builder.create();
mDialog.getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
your code isn't working because the method that you are using, setItemChecked, doesn't change the selected state when receive a false and is working on CHOICE_MODE_SINGLE, which is the normal behaviour of a group of radio buttons. You can see it by yourself with "Go To Implementation" in Android Studio (Ctrl + RightClick over the method).
Also, it's not recommended to use checkboxes for a single choice selector as it will confuse your users. You can easily get radio buttons replacing setMultipleChoiceItems by setSingleChoiceItems. It also apply the single choice mode to your ListView, so you can get rid of your last line.
To allow the user to perform an empty selection with radio buttons you have mainly 2 options:
Add an extra items to your list representing the empty selection option. Label it as "None", "Uncheck" or something similar
Add an extra button to your dialog to dismiss the dialog and return an empty selection.
Here you have a sample of implementation of the first option adding dynamically the empty item for a better re-usability ;)
Screenshot
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String title = "Select your favourite language";
String[] items = {"English", "Spanish", "Chinese", "Java"};
String emptyItemTitle = "NONE OF THEM";
int initialSelection = 0;
showSingleChoiceDialogWithNoneOption(title, items, initialSelection, emptyItemTitle);
}
private void showSingleChoiceDialogWithNoneOption(String title, final String[] titleItems, int initialSelection, String emptyItemTitle ) {
final String[] extendedItems = addEmptyItem(titleItems, emptyItemTitle);
final int[] selectedPosition = {initialSelection};
new AlertDialog.Builder(this)
.setTitle(title)
.setSingleChoiceItems(extendedItems, initialSelection, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedPosition[0] = which;
Log.d("MyTag", String.format("Selected item '%s' at position %s.", extendedItems[which], which));
}
})
.setNegativeButton("Cancel", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("MyTag", String.format("Confirmed the selection of '%s' at position %s.", extendedItems[selectedPosition[0]], selectedPosition[0]));
onSelectionConfirmed(selectedPosition[0]);
}
})
.show();
}
#NonNull
private String[] addEmptyItem(String[] titleItems, String emptyTitle) {
String[] tempArray = new String[titleItems.length + 1];
tempArray[0] = emptyTitle;
System.arraycopy(titleItems, 0, tempArray, 1, titleItems.length);
return tempArray;
}
private void onSelectionConfirmed(int position) {
if (position==0){
//Handle your empty selection
}else{
//Selected item at position
}
}
}

Change Scroll direction of number picker dialog android

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.

Get selected list item in alert dialog with split string

I have string array in strings.xml with the country phone numbers and the country name separated by a comma.
Now I want to show this list in a dialog and show the country phone number of the selected country in an edittext.
The list is shown, I can click an item and a number w/o the country name is shown in the edittext but unfortunately it's always the same value. It looks like I don't get the clicked item but iterate though the complete list and get something back.
Here's the code of the alert dialog:
private void selectCountry() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.choose_country);
final String[] names = getResources().getStringArray(R.array.Countries);
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String CountryZipCode = "";
for (int i = 0; i < names.length; i++) {
String[] g = names[i].split(",");
CountryZipCode = g[0];
}
countrycode.setText("+" + CountryZipCode);
}
});
AlertDialog alert = builder.create();
alert.show();
}
And here's a snippet of the array list from strings.xml:
<string-array name="Countries" >
<item>93,Afghanistan</item>
<item>355,Albania</item>
<item>213,Algeria</item>
<item>376,Andorra</item>
<item>244,Angola</item>
</string-array>
Thanks a lot in advance!
is it always the last one?
because if i am reading your code correctly thats what you are doing..
shouldn't you be saying:
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String CountryZipCode = "";
//for (int i = 0; i < names.length; i++) {
String[] g = names[item].split(",");
CountryZipCode = g[0];
//}
countrycode.setText("+" + CountryZipCode);
}
});

Dialog Boxes appearing as stack in android

I am creating 2 dialog boxes at a time, 2nd dialog box appears first(users input goes to it first) then for the 1st dialog box, like a stack. But I want it in reverse order means after giving the input to the first dialog box only second dialog must appear.
simply saying...., I created dialog box with in a for loop if the iteration is 2 then it will create 2 dialog boxes. I want second dialog box must appear after input is given to the first dialog box.
for(int i=0;i<playerCount;i++) {
AlertDialog.Builder outOfGameBuilder = new AlertDialog.Builder(context);
outOfGameBuilder.setTitle("Out Of Game");
//find max count to rejoin
final int finalMaxCount = maxCount;
StringBuilder message = new StringBuilder();
final TextView name = (TextView)findViewById(i+10);
message.append(name.getText().toString());
message.append(" is out of game, Wants to rejoin on ");
message.append(String.valueOf(maxCount+1));
outOfGameBuilder.setMessage(message);
outOfGameBuilder.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
SharedPreferences myPref = getSharedPreferences(MyPref, MODE_PRIVATE);
int x = myPref.getInt("i", 0);
//Log.d("name", name.getText().toString());
flag[x] = true;
int maxRow = myPref.getInt("column", 0);
for(int j=0;j<playerCount;j++) {
TextView countView = (TextView)findViewById(j+100);
Log.d("flag:"+j, ":"+flag[j]);
if(Integer.parseInt(countView.getText().toString()) > finalMaxCount && flag[j]) {
ed[maxRow][j].setText(String.valueOf(finalMaxCount+1));
countView.setText(String.valueOf(finalMaxCount+1));
} else if(flag[j]) {
ed[maxRow][j].setText(countView.getText().toString());
}
}
});
outOfGameBuilder.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Log.d("name", name.getText().toString());
arg0.cancel();
}
});
AlertDialog outOfGameDialog = outOfGameBuilder.create();
outOfGameDialog.show();
}

Android AlertDialog wait for result in calling activity

I am trying to use an AlertDialog in my app to select the quantity of an item. The problem is that the activity that calls the AlertDialog doesn't wait for it to update the item before it adds it to the SQLite Database and change intents.
At the moment, the QuantitySelector (AlertDialog) appears, then disappears straight away and changes the MealActivity class (which is just a ListView that reads from the database) through the intent change with an update to the database with quantity 0.
I need the Activity to wait for the AlertDialog to close before it updates the database.
What would be the correct way of implementing this?
Here is some code for you:
QuantitySelector (which runs the alertdialog):
public class QuantitySelector{
protected static final int RESULT_OK = 0;
private Context _context;
private DatabaseHandler db;
private HashMap<String, Double> measures;
private Item item;
private View v;
private EditText quan;
private NumberPicker pick;
private int value;
private Quantity quantity;
/**
* Function calls the quantity selector AlertDialog
* #param _c: The application context
* #param item: The item to be added to consumption
* #return The quantity that is consumed
*/
public void select(Context _c, Item item, Quantity quantity){
this._context = _c;
this.item = item;
this.quantity = quantity;
db = new DatabaseHandler(_context);
//Get the measures to display
createData();
//Set up the custom view
LayoutInflater inflater = LayoutInflater.from(_context);
v = inflater.inflate(R.layout.quantity_selector, null);
//Set up the input fields
quan = (EditText) v.findViewById(R.id.quantityNumber);
pick = (NumberPicker) v.findViewById(R.id.numberPicker1);
//Set up the custom measures into pick
pick.setMaxValue(measures.size()-1);
pick.setDisplayedValues(measures.keySet().toArray(new String[0]));
//Start the alert dialog
runDialog();
}
public void createData(){
measures = new HashMap<String, Double>();
//Get the measurements from the database
if(item!=null){
measures.putAll(db.getMeasures(item));
}
//Add grams as the default measurement
if(!measures.keySet().contains("grams")){
//Add grams as a standard measure
measures.put("grams", 1.0);
}
}
public void runDialog(){
AlertDialog dialog = new AlertDialog.Builder(_context).setTitle("Select Quantity")
.setView(v)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Change the consumption to the new quantity
if(!quan.getText().toString().matches("")){
value = Integer.parseInt(quan.getText().toString());
//Check if conversion from other units is needed
String s[] = pick.getDisplayedValues();
String a = s[pick.getValue()];
//Convert the chosen measure back to grams
if(!a.equals("grams")){
for(String m : measures.keySet()){
if(m==a){
value = (int) (value * measures.get(m));
}
}
}
}
quantity.setQuantity(value);
dialog.dismiss();
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}
}
The method from favouritesAdapter (which calls the alertdialog):
add.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
QuantitySelector q = new QuantitySelector();
Quantity quan = new Quantity();
q.select(_context, db.getItem(p.getID()), quan);
db.addConsumption(p.getID(), p.getFavouriteShortName(), quan.getQuantity(), "FAVOURITE");
Intent intent = new Intent(_context,MealActivity.class);
_context.startActivity(intent);
}
});
All help is appreciated :)
Use Async task and update data in doInBackGround and in onPostExecute method Show Dialog.
The way you want to go about this is to actually start the next intent when the person presses the positive button. In short, you need to be starting your next Activity in the OnClickListener that is attached to your positive button of your AlertDialog.
public void runDialog(){
AlertDialog dialog = new AlertDialog.Builder(_context).setTitle("Select Quantity")
.setView(v)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Change the consumption to the new quantity
if(!quan.getText().toString().matches("")){
value = Integer.parseInt(quan.getText().toString());
//Check if conversion from other units is needed
String s[] = pick.getDisplayedValues();
String a = s[pick.getValue()];
//Convert the chosen measure back to grams
if(!a.equals("grams")){
for(String m : measures.keySet()){
if(m==a){
value = (int) (value * measures.get(m));
}
}
}
}
quantity.setQuantity(value);
dialog.dismiss();
//The only catch now is passing through your _context
Intent intent = new Intent(_context,MealActivity.class);
_context.startActivity(intent);
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}
Actually your problem is you are calling the start activity for MealACtivity before destroying the alert dialogue so can update your code as follows:
Update your method which calls the alertdialogue by this code:
add.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
QuantitySelector q = new QuantitySelector();
Quantity quan = new Quantity();
q.select(_context, db.getItem(p.getID()), quan);
db.addConsumption(p.getID(), p.getFavouriteShortName(), quan.getQuantity(), "FAVOURITE");
/* Intent intent = new Intent(_context,MealActivity.class);
_context.startActivity(intent);*/
}
});
and update your Quantity Selector class with the following :
public class QuantitySelector{
protected static final int RESULT_OK = 0;
private Context _context;
private DatabaseHandler db;
private HashMap<String, Double> measures;
private Item item;
private View v;
private EditText quan;
private NumberPicker pick;
private int value;
private Quantity quantity;
/**
* Function calls the quantity selector AlertDialog
* #param _c: The application context
* #param item: The item to be added to consumption
* #return The quantity that is consumed
*/
public void select(Context _c, Item item, Quantity quantity){
this._context = _c;
this.item = item;
this.quantity = quantity;
db = new DatabaseHandler(_context);
//Get the measures to display
createData();
//Set up the custom view
LayoutInflater inflater = LayoutInflater.from(_context);
v = inflater.inflate(R.layout.quantity_selector, null);
//Set up the input fields
quan = (EditText) v.findViewById(R.id.quantityNumber);
pick = (NumberPicker) v.findViewById(R.id.numberPicker1);
//Set up the custom measures into pick
pick.setMaxValue(measures.size()-1);
pick.setDisplayedValues(measures.keySet().toArray(new String[0]));
//Start the alert dialog
runDialog();
}
public void createData(){
measures = new HashMap<String, Double>();
//Get the measurements from the database
if(item!=null){
measures.putAll(db.getMeasures(item));
}
//Add grams as the default measurement
if(!measures.keySet().contains("grams")){
//Add grams as a standard measure
measures.put("grams", 1.0);
}
}
public void runDialog(){
AlertDialog dialog = new AlertDialog.Builder(_context).setTitle("Select Quantity")
.setView(v)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Change the consumption to the new quantity
if(!quan.getText().toString().matches("")){
value = Integer.parseInt(quan.getText().toString());
//Check if conversion from other units is needed
String s[] = pick.getDisplayedValues();
String a = s[pick.getValue()];
//Convert the chosen measure back to grams
if(!a.equals("grams")){
for(String m : measures.keySet()){
if(m==a){
value = (int) (value * measures.get(m));
}
}
}
}
quantity.setQuantity(value);
Intent intent = new Intent(_context,MealActivity.class);
_context.startActivity(intent);
dialog.dismiss();
}
})
.setNegativeButton("Cancel", null).create();
dialog.show();
}

Categories

Resources