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);
}
});
Related
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
}
}
}
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
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();
}
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
When implementing setMultiChoiceItems with a cursor, you have to specify an isCheckedColumn.
The problem, as articulated on other sites, is that when users select an item from the list the checkbox does not update. Some have suggested updating the SqLite table each time a user selects an item, but this did not work in my application. Here is the solution I came up with.
This is what I came up with:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int myDialogChoice = getArguments().getInt("whichDialog");
mSelectedItems = new ArrayList(); // Where we track the selected items
mCurrentFavoritesSelection = new ArrayList();
myDataBaseAdapter = new AthleteDbAdapter(getActivity());
// int myAthleteId;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
switch(myDialogChoice) {
case Select_From_Favorites:
myCursorFromSqLite = myDataBaseAdapter.fetchAllFavorites(getActivity());
// You need a Primative Boolean Array to specify which items were selected last time.
boolean[] booleanPrimativeArray = new boolean[myCursorFromSqLite.getCount()];
final ArrayList mArrayListOfIDs = new ArrayList();
ArrayList<Boolean> myBooleanList = new ArrayList<Boolean>();
// This array will be the choices that appear in the Dialog.
ArrayList<String> mArrayListOfNames = new ArrayList<String>();
myCursorFromSqLite.moveToFirst();
/* Populate Arrays
*
*/
int iCount = 0;
while(!myCursorFromSqLite.isAfterLast()) {
// put _id's from SqLite data into an array.
mArrayListOfIDs.add(Integer.valueOf(
myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex(KEY_ROWID))));
// put series of booleans into Primative Array depending upon whether user selected them last time.
if(Integer.valueOf(myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex("checked"))) == 1){
booleanPrimativeArray[iCount] = true;
mSelectedItems.add(
Integer.valueOf(myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex(KEY_ROWID)))
);
// I kept track of what selections from last time were.
mCurrentFavoritesSelection.add(
Integer.valueOf(myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex(KEY_ROWID)))
);
} else booleanPrimativeArray[iCount] = false;
iCount++;
mArrayListOfNames.add(myCursorFromSqLite.getString(myCursorFromSqLite.getColumnIndex("fullName")));
myCursorFromSqLite.moveToNext();
}
// Change the ArrayList of names to a Char Sequence
CharSequence[] charSeqOfNames = mArrayListOfNames.toArray(new CharSequence[mArrayListOfNames.size()]);
try{
myCursorFromSqLite.close();
} catch (Throwable t) {
Log.e(APP_TAG,"Error closing myCursorFromSqLite Cursor " + t);
}
builder.setTitle(R.string.pick_athletes)
.setMultiChoiceItems(charSeqOfNames, booleanPrimativeArray,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, build an array containing the selected items _id's.
mSelectedItems.add((Integer) mArrayListOfIDs.get(which));
} else if (mSelectedItems.contains((Integer) mArrayListOfIDs.get(which))) {
// Else, if the user changes his mind and de-selects an item, remove it
mSelectedItems.remove((Integer) mArrayListOfIDs.get(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.pullathletesbutton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
Log.d(APP_TAG,"Call something");
mListener.onDialogPositiveClick(PickListDialog.this, mSelectedItems, mCurrentFavoritesSelection);
}
})
.setNegativeButton(R.string.cancelbutton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
This worked well. The user can change his mind without affecting the underlying database and the checkmarks update properly. Once the user has finalized his choices, he hits the "positive" button and the database is updated.