I'm using alert dialog to show some records.those records are comming from db and display in Alertdialog.when user click on item i want to get item name to Log.this is my code.it show item as [test] but i want it showing as test
ArrayList arrayList and String [] categoryStrings initialized on top
List<Video> vd=Video.findWithQuery(Video.class, "select * from Video");
if (vd.size()>0) {
for (Video v : vd) {
arrayList.add(v.getTitle());
}
final List<String> list = Arrays.asList(arrayList.toString());
categoryStrings=new String[list.size()];
categoryStrings=list.toArray(categoryStrings);
AlertDialog.Builder alert = new AlertDialog.Builder(Editmedia.this);
alert.setTitle("Media List");
alert.setCancelable(false);
final int selected = 0; // or whatever you want
alert.setSingleChoiceItems(categoryStrings, selected, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//onclick
String categoryString = categoryStrings[item];
Log.d("sel", " " + item+" "+categoryString);
edit();
}
});
alert.show();
log value showing
0 [test] i want it as test
Log
Try this, it should help
String categoryString = categoryStrings[item];
categoryString = categoryString.replaceAll("[\\p{Ps}\\p{Pe}]","");
Log.d("sel", " " +" "+categoryString);
[EDIT]
String categoryString = categoryStrings[item];
categoryString = categoryString.replace("[","");
categoryString = categoryString.replace("]","");
Log.d("sel", " " +" "+categoryString);
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Media List");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
arrayAdapter.clear();
for (int i = 0; i < list.size(); i++) {
Log.i(LOG_TAG, list.get(i));
arrayAdapter.add(list.get(i));
}
builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), list.get(which),
Toast.LENGTH_LONG).show();
}
});
builder.setPositiveButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
Related
I only want my AlertDialog to be dismissed when certain conditions are met (when name and surname given are valid) - else it should always be on top of the parent view. My code is this:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final TextView instructions = new TextView(this);
instructions.setText(R.string.alert_enter_data);
final EditText name = new EditText(this);
name.setHint(R.string.name);
final EditText surname = new EditText(this);
surname.setHint(R.string.surname);
LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(instructions);
ll.addView(name);
ll.addView(surname);
alert.setView(ll);
alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name_txt = name.getText().toString();
String surname_txt = surname.getText().toString();
if ((name_txt.length() > 1) && (surname_txt.length() > 1)) {
dialog.dismiss();
}
}
});
final AlertDialog alert_dialog = alert.create();
alert_dialog.setCanceledOnTouchOutside(false);
alert_dialog.show();
With this code the AlertDialog disappears when the button is pressed, regardless of the input text. I then tried this:
alert_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name_txt = name.getText().toString();
String surname_txt = surname.getText().toString();
String email_txt = email.getText().toString();
String cellphone_txt = cellphone.getText().toString();
String postcode_txt = postcode.getText().toString();
if ((name_txt.length() > 1) && (surname_txt.length() > 1) && (email_txt.length() > 4)) {
if (debug_mode) {Log.i(TAG,"clause 1");}
String data_to_upload = name_txt + ", " + surname_txt + ", " + email_txt + ", "+ cellphone_txt + ", " + postcode_txt + "\n";
// upload_to_github(data_to_upload);
alert_dialog.dismiss();
}
}
});
}
});
But this way I get not Button at all. The Alert Dialog only contains the EditText fields.
alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
and
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
both are different buttons.
try
Button b = alert.getButton(AlertDialog.BUTTON_NEUTRAL);
Its a game in which at the end activity the score is displayed But before that the input alert box is displayed where user need to add their name,and that name and score should go to the database. score is getting stored but not the name. how to get name from input alert dialog box and set it on db.insertScore(Score,Name).how am i suppose to add input value of alert dialog box to extra.getString(""); there is getter & setter method.here is my code
Bundle extra = getIntent().getExtras();
if (extra != null)
{
showInputDialog();
final String Name=extra.getString("");
final int Score = extra.getInt("SCORE");
final int totalQuestion = extra.getInt("TOTAL");
int correctAnswer = extra.getInt("CORRECT");
txtTotalScore.setText(String.format("SCORE : %d", Score));
txtTotalQuestion.setText(String.format("PASSED : %d/%d", correctAnswer, totalQuestion));
progressBarResult.setMax(totalQuestion);
progressBarResult.setProgress(correctAnswer);
db.insertScore(Score, Name);
}
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Done.this);
View promptView = layoutInflater.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Done.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String Name = editText.getText().toString();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
try this
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Done.this);
View promptView = layoutInflater.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Done.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String Name = editText.getText().toString();
//call a function which do in background and have a connection with database
new setname(Name);
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void setname(final String name){
#Override
protected String doInBackground(String... params){
Data = new HashMap<String, String>();
Data.put("name", name);
try {
JSONObject json = Connection.UrlConnection("http://url", Data);
int succ = json.getInt("success");
if (succ == 0) {
s = "false";
} else {
s = "true";
}
} catch (Exception e) {
}
return s;
}
}
}
Also write a php file which code insert to db
Make the Name variable global and don't use the following line :
String Name;
Bundle extra = getIntent().getExtras();
if (extra != null)
{
showInputDialog();
final int Score = extra.getInt("SCORE");
final int totalQuestion = extra.getInt("TOTAL");
int correctAnswer = extra.getInt("CORRECT");
txtTotalScore.setText(String.format("SCORE : %d", Score));
txtTotalQuestion.setText(String.format("PASSED : %d/%d", correctAnswer, totalQuestion));
progressBarResult.setMax(totalQuestion);
progressBarResult.setProgress(correctAnswer);
db.insertScore(Score, Name);
}
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Done.this);
View promptView = layoutInflater.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Done.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Name = editText.getText().toString();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
I am making an android app that asks for the users to select a country via spinner.
When the user opens the app first time, user selects a country from list.
Then when app opens second time, I want the same country to be selected. I don't want user to select the country every time the app is opened.
How to do that?
You can use SharedPreferences to store the selection the first time that the user selects a country, and then use SharedPreferences again for the app to remember the selection, when the user returns a second time.
To store the selection in a SharedPrefence:
SharedPreferences.Editor editor = getPreferences(0).edit();
int selectedPosition = yourSpinner.getSelectedItemPosition();
editor.putInt("spinnerSelection", selectedPosition);
editor.apply();
To load the selection onto the spinner when reusing the app:
SharedPreferences prefs = getPreferences(0);
yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
Hope this solves your issue :)
Try this one
String citySelected
final CharSequence[] items = {" abc ", " def ", " ghi ", " jkl ", " mno ",
" pqr ", " stu ",
" vwzyz "};
List<String> lanSelected = new ArrayList<>();
final boolean[] checkedItems = new boolean[]{false, false, false, false, false, false, false, false};
List<String> temp = new ArrayList<>();
for (int o = 0; o < items.length; o++) {
temp.add(items[o].toString());
}
final List<Integer> seletedItems = new ArrayList();
if (citySelected.equals("") || citySelected == null) {
} else
lanSelected = Arrays.asList(citySelected.split(","));
if (lanSelected.size() > 0) {
for (int p = 0; p < lanSelected.size(); p++) {
String x = lanSelected.get(p);
int xpos = temp.indexOf(x);
if (xpos != -1) {
checkedItems[xpos] = true;
seletedItems.add(xpos);
}
}
}
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(context);
}
// arraylist to keep the selected items
AlertDialog dialog = builder
.setTitle("city")
.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
seletedItems.add(indexSelected);
} else if (seletedItems.contains(indexSelected)) {
// Else, if the item is already in the array, remove it
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String city = "";
for (int i = 0; i < seletedItems.size(); i++) {
if (i == seletedItems.size() - 1) {
city = city + items[Integer.parseInt(seletedItems.get(i).toString())];
} else {
city = city + items[Integer.parseInt(seletedItems.get(i).toString())] + ",";
}
}
btn_city_todisplay.setText(city);
dialog.dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on Cancel
}
}).create();
dialog.show();
Use spinner method to show selected item
spinner.setSelection(position);
Here position is the last selected position
You can use sharedPreference to store the country you have chosen, then search the map and find the position of country in your array, finally use setSelection(int position)to set the default country
Good Day,
I created a method showDialog which will show an Alert Dialog and will list multiple data that I can select of. My problem is when I click OK, the next method (myMethod()) i want to call is not being called. Can someone help me with this? Here is my code:
private void showDialog(List<String> list) {
final CharSequence[] dialogList= list.toArray(new CharSequence[list.size()]);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(SharingActivity.this);
builderDialog.setTitle("Select Item");
int count = dialogList.length;
boolean[] is_checked = new boolean[count];
String result = "";
builderDialog.setMultiChoiceItems(dialogList, is_checked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked) {
}
});
builderDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ListView list = ((AlertDialog) dialog).getListView();
// make selected item in the comma seprated string
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < list.getCount(); i++) {
boolean checked = list.isItemChecked(i);
if (checked) {
if (stringBuilder.length() > 0) stringBuilder.append(",");
stringBuilder.append(list.getItemAtPosition(i));
}
}
myMethod(stringBuilder.toString()); //this is the method
}
});
builderDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((TextView) findViewById(R.id.text)).setText("Click here to open Dialog");
}
});
AlertDialog alert = builderDialog.create();
alert.show();
}
Here is myMethod:
private void myMethod(String stringFriend){
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("image");
Bitmap image = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
//Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(image)
.setCaption("")
.build();
List<String> peopleIds = new ArrayList<String>();
peopleIds.add(stringFriend);
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.setPeopleIds(peopleIds)
.build();
ShareApi.share(content, null);
}
I have a spinner, how can i bind it to an AlertDialog? It is possible to do that?
please try this :
public class WvActivity extends Activity {
TextView tx;
String[] s = { "India ", "Arica", "India ", "Arica", "India ", "Arica",
"India ", "Arica", "India ", "Arica" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayAdapter<String> adp = new ArrayAdapter<String>(WvActivity.this,
android.R.layout.simple_spinner_item, s);
tx= (TextView)findViewById(R.id.txt1);
final Spinner sp = new Spinner(WvActivity.this);
sp.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
sp.setAdapter(adp);
AlertDialog.Builder builder = new AlertDialog.Builder(WvActivity.this);
builder.setView(sp);
builder.create().show();
}
}
Instead why don't you use an activity and set it to Dialog style. Should be like the same visual approach and you can design your dialog just as you want it.
public void CreateAlertDialog1() {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.note_dialog, null);
final EditText etName = (EditText) alertLayout.findViewById(R.id.enter_name);
final TextView call_date = alertLayout.findViewById(R.id.call_date);
call_date.setVisibility(View.GONE);
date_time_display = alertLayout.findViewById(R.id.date_time_display);
date_time_select = alertLayout.findViewById(R.id.date_time_select);
final Spinner spSex = (Spinner) alertLayout.findViewById(R.id.spinner);
String[] status_note = new String[] {
"Laceflower",
"Sugar maple",
"Mountain mahogany",
"Butterfly weed"
};
final List<String> plantsList = new ArrayList<>(Arrays.asList(status_note));
// Initializing an ArrayAdapter
#SuppressLint({"NewApi", "LocalSuppress"}) final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
Objects.requireNonNull(getActivity()),R.layout.spinner_item,plantsList);
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
spSex.setAdapter(spinnerArrayAdapter);
date_time_select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
});
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(client_name_display);
alert.setIcon(getActivity().getResources().getDrawable(R.drawable.addnote));
alert.setView(alertLayout);
alert.setCancelable(false);
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity().getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
OkHttpHandler okHttpHandler = new OkHttpHandler(status, res, start_date_time, end_date_time, etName.getText().toString());
okHttpHandler.execute("https://management.reflectdm.com/api/call-management");
}
});
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String user = etName.getText().toString();
String sex = String.valueOf(spSex.getSelectedItem());
//Toast.makeText(getBaseContext(), "Name: " + user + "\nBirthday: " + bday + "\nSex: " + sex + "\nHungry: " + hungry, Toast.LENGTH_SHORT).show();
OkHttpHandler okHttpHandler = new OkHttpHandler(status, res, start_date_time, end_date_time, etName.getText().toString());
okHttpHandler.execute("https://management.reflectdm.com/api/call-management");
}
});
AlertDialog dialog = alert.create();
dialog.show();
}