Change Scroll direction of number picker dialog android - 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.

Related

Populate List<String> with AlertDialog Input

Building my first app and can't find a solution by myself.
What my app does:
MainActivity prompts user to input player amount
presses Ok, input passed to next activity
now I want, that the user is prompted to input the player names, one by one with an AlertDialog. Those names, should be stored in an Array.
My code so far:
public class MainScreen extends AppCompatActivity {
private static final String TAG = MainScreen.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
try {
Intent intent = getIntent();
final int sumPlayers = getIntent().getIntExtra("sumPlayers", 0);
final List<String> playerNames = new ArrayList<>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText input = new EditText(getBaseContext());
input.setTextColor(Color.BLACK);
//input.setSingleLine();
for (int c=0; c<sumPlayers; c++) {
builder.setTitle("Input Player Name");
builder.setView(input);
builder.setPositiveButton("ADD", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
playerNames.add(input.getText().toString());
}
});
builder.show();
}
ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(this, R.layout.player_list_item, R.id.editText, playerNames);
ListView listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(playerAdapter);
} catch (Exception e) {
System.out.println("2te Act");
Log.e(TAG, "Error#: ", e);
}
}
}
I get this Exception # builder.show();
Java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
It's working without the for loop except one minor problem.
When I set the input field to setSingleLine(); the listView stays empty.
You are creating a single AlertDialog.Builder and repeatedly setting the title, view, and positive button with different values. You likely need to move this logic inside the for loop:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText input = new EditText(getBaseContext());
input.setTextColor(Color.BLACK);
//input.setSingleLine();

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

number picker doesn't show values

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

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