Displaying ListView in alertDailog android - android

When the user clicks the item of list View a alert Dialog box will be displayed to the user with options like "view","delete" or "update"
the list view item. Clicking on the list view item for the first time displays the alert Dialog with options but when i click another list View item or the same list View item the second time the app crashes.Thanks in advance.
Error :java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
//The main list displayed when the user log in successfully
ListView = (ListView) findViewById(R.id.list);
ListView2 = new ListView(this); //List to be displayed in the alert Dailog box
ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long i = ListView.getItemIdAtPosition(position);
showAlertDailog();//The dialog box method
}
});
if(mCursorAdapter == null) //To check if the list is empty
{
TextView emptyTextView = (TextView) findViewById(R.id.empty);
emptyTextView.setText("No Notes");
ListView.setEmptyView(emptyTextView);
}else {
mCursorAdapter = new DataCursorAdapter(this, null);
ListView.setAdapter(mCursorAdapter);
}
public void showAlertDailog()
{
String [] items = {"View","Delete","Update"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.item_todo_2,R.id.textView4,items);
ListView2.setAdapter(adapter);
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(HomeActivity.this);
builder.setView(ListView2)
.setCancelable(false)
.setPositiveButton("Close",null);
android.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
}

ArrayList<String> arrayList = new ArrayList<String>();
CharSequence[] animals = arrayList.toArray(new String[arrayList.size()]);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setItems(animals, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String selectedText = animals[item].toString();
}
});
AlertDialog alertDialogObject = dialogBuilder.create();
alertDialogObject.show();
This is simple way to display list inside alert dialog, where in arraylist just add string whatever you have to display inside alert dialog list.

It is exactly what you need
public class MainActivity extends Activity implements OnClickListener {
private Button mDoneButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDoneButton = (Button) findViewById(R.id.done_button);
mDoneButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final CharSequence[] items = {
"Rajesh", "Mahesh", "Vijayakumar"
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Do something with the selection
mDoneButton.setText(items[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
http://rajeshvijayakumar.blogspot.in/2013/04/alert-dialog-dialog-with-item-list.html
OUTPUT

lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String[] listItems = { "Colour", "Font Size", };
if (listItems[position].equals("Font Size")) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Settings.this );
// set title
alertDialogBuilder.setTitle("Choose Font Size");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
});

public void showAlertDailog(Context context) {
ListView listView=new ListView(context);
yourLayout.LayoutParams params= yourLayout.LayoutParams(Yourlayout.LayoutParams.MATCH_PARENT,Yourlayout.LayoutPa
rams.MATCH_PARENT);
listview.setLayoutParams(params);
String [] items = {"View","Delete","Update"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
listView.setAdapter(adapter);
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
builder.setView(listView)
.setCancelable(false)
.setPositiveButton("Close",(dialog,something)->{dialog.dismiss()});
android.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
}

Related

Checkbox state in listview onItemLongClick

I have a listview in which when you select a row, it's checkbox becomes checked / unchecked. However, I have a onItemLongClick that displays a dialog.
Problem is when I long-click a row in the listview, it becomes checked and I don't want that to happen, I just need it to display a dialog. This is confusing me because the onItemClick is also called when I use onItemLongClick.
Here's the code for onItemClick:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkmark);
TextView tv3 = (TextView)view.findViewById(R.id.tx_amount);
String shitts = listView.getItemAtPosition(position).toString();
HashMap<String, String> data = new HashMap<>();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
try {
checkBox.setChecked(!checkBox.isChecked());
String[] a = shitts.split(", ");
String[] sep = a[0].split("=");
String betamount = sep[1];
String[] sepx = a[2].split("=");
String betnumber = sepx[1];
String showbetnumber = betnumber.replaceAll("[;/:*?\"<>|&{}']","");
if(checkBox.isChecked()){
hash.put(showbetnumber,tv3.getText().toString());
}else {
tv3.setText(betamount);
checked.removeAll(Collections.singletonList(position));
hash.remove(showbetnumber,tv3.getText().toString());
}
}catch (Exception e){
}
}
});
and here's the code for onItemLongClick
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String x = input.getText().toString();
txAmt.setText(x);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return false;
}
});
Any help is appreciated!
Create a boolean isLongClick and set it to false.
onItemLongClick(), set isLongClick to true.
On your dialog, set isLongClick to false again when any button is clicked or if the dialog was dismissed.
Finally, wrap all your code inside onItemClick() in:
if (!isLongClick) {
// onItemClick() code
}
The source of this solution

AlertDialog - do not dismiss on item click

OK so I am creating an ArrayAdapter and using it in my Alert Dialog because I don't want to show the default radio buttons on SingleItemSelection dialog.
Instead I want to change the background of the item that is selected, and then when the user presses the positive button I will perform the action related to the item that has been selected.
private void showAlertDialog()
{
final String[] options = getResources().getStringArray(R.array.dialog_options);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, options);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("My Dialog");
dialogBuilder.setAdapter(adapter, new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "item clicked at index " + which, Toast.LENGTH_LONG).show();
// Here I need to change the background color of the item selected and prevent the dialog from being dismissed
}
});
//String strOkay = getString(R.string.okay);
dialogBuilder.setPositiveButton("OK", null); // TODO
dialogBuilder.setNegativeButton("Cancel", null); // nothing simply dismiss
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
There are two problems I'm trying to tackle.
How do I prevent the dialog from being dismissed when the user clicks on an item
How do I change the background of the item that has been selected when the user clicks on it
To prevent dialog from dismissing on item click you can use AdapterView.OnItemClickListener instead of DialogInterface.OnClickListener.
Like this:
dialogBuilder.setAdapter(adapter, null);
...
AlertDialog dialog = dialogBuilder.create();
alertDialog.getListView().setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do your stuff here
}
});
You can set custom ListView as content of AlertDialog and set OnItemClickListener
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String[] items = ...;
ListView list = new ListView(this);
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int pos, long id) {
...
}
});
builder.setView(list);
and then save reference to dialog
mDialog = builder.show();
in order to dismiss it if necessary
mDialog.dismiss();
How do I prevent the dialog from being dismissed when the user clicks on an item
How do I change the background of the item that has been selected when the user clicks on it
Here is example
public class MainActivity extends AppCompatActivity {
private static final String listFragmentTag = "listFragmentTag";
private static final String data[] = {"one", "two", "three", "four"};
public MainActivity() {
super();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnClick(View v) {
ListFragment lf = new ListFragment();
lf.show(getSupportFragmentManager(), listFragmentTag);
}
public static class ListFragment extends DialogFragment {
#Override #NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
adb.setIcon(android.R.drawable.ic_dialog_info)
.setTitle("List")
.setItems(data, null)
.setPositiveButton("OK", null); // pass your onClickListener instead of null
// to keep dialog open after click on item
AlertDialog ad = adb.create();
ad.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
private int colorOrg = 0x00000000;
private int colorSelected = 0xFF00FF00;
private View previousView;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// restoring color of previous view
if(previousView != null) {
previousView.setBackgroundColor(colorOrg);
}
// changing items's BG color
view.setBackgroundColor(colorSelected);
previousView = view;
}
});
return ad;
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
}
}
}
You can use setCanceledOnTouchOutside(false) or setCanceleable(false).
Set selector for the root element tag of the dialog layout xml.

Want to update the list in every entry view?

i'am having a list with textview, many data's are flowing in list and having one textview in xml....problem is i want to update the every textview entry in the list..i want to update the (TAG_QTY) textview in list when every value entry...
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_BARCODE, TAG_DIVISION, TAG_MRP,TAG_QTY}, new int[] {
R.id.txt, R.id.txt1, R.id.mrp,R.id.qty1 });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//String name = ((TextView) view.findViewById(R.id.qty1)).getText().toString();
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
//final View textEntryView;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
fourth = (TextView)findViewById(R.id.qty1);
userInput = (EditText)promptsView.findViewById(R.id.editTextDialogUserInput);
//String ed = userInput.getText().toString();
//final int ed= Integer.parseInt(userInput.getText().toString());
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
String ed = userInput.getText().toString().trim();
fourth.setText(ed);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
);
In order to get the list view child
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View c = lv.getChildAt(position);
// c is your list view child which is clicked
final TextView tv = (TextView) c.findViewById(R.id.qty1);
// tv is your textview of whom vwlue you have to change.
//changes the value of textview here and den notify data set changed and refresh the list.
}
});

Show list view in a popup window - Android

I'm working on a project in Android and I have a problem.
I have an activity which includes three buttons, edit text and a list view.
I want to change that implementation and to show the list view on a new popup window only when the user press the select all button.
I've added my code, thanks.
public class Notepadv1 extends ListActivity implements OnClickListener {
private WordsDbAdapter mDbHelper;
private Button selectAllButton;
private PopupWindow mPopup;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectAllButton = (Button)findViewById(R.id.selectAll);
selectAllButton.setOnClickListener(this);
mDbHelper = new WordsDbAdapter(this);
mDbHelper.open();
fillData();
}
public void onClick(View v) {
switch(v.getId()){
case(R.id.selectAll):
selectAll();
break;
}
}
private void selectAll(){
}
private void fillData() {
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { WordsDbAdapter.KEY_WORD };
int[] to = new int[] { R.id.text1 };
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.words_row, c, from, to);
setListAdapter(notes);
}
}
Show a simple Alert Dialog with a list:
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
Yes you can do it.
1st way:
define an activity as Dialog with the below attribute in AndroidManifest.xml file:
<activity android:theme="#android:style/Theme.Dialog" />
2nd way:
You can inflate the XML layout inside the dialog as below:
Dialog dialog = new Dialog(context);
LayoutInflater li = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.my_layout, null, false);
dialog.setContentView(v);
dialog.show();
for example:
edit: link fixed
Android Dialog with ListView.
If using a custom ArrayAdapter, use setAdapter():
AlertDialog.Builder builder = new Builder(this)
.setTitle("Dialog Title")
.setAdapter(new CustomAdapter(context, items, ...), (dialog, itemPosition) -> {
// Handle item click
});
builder.show();

Access controls within custom alert dialog in android

When displaying custom dialog box which is showing textView and EditView. How can i access these elements within dialog. Below is the code which is giving error.
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_text_entry)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
string = uetd.getText().toString() + ":" + petd.getText().toString(); /////producing error
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked cancel so do some stuff */
}
})
.create();
public class listdemo extends ListActivity {
/** Called when the activity is first created. */
private static final int DIALOG_TEXT_ENTRY = 7;
EditText uetd;
EditText petd;
SharedPreferences.Editor editor;
String string;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
uetd=(EditText)findViewById(R.id.username_edit);
petd=(EditText)findViewById(R.id.password_edit);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
showDialog(DIALOG_TEXT_ENTRY);
}
});
}
}
Instead of returning the dialog immedately with return new AlertDialog.builder....and so on....you should save an instance of the dialog by creating a class variable just like this
AlertDialog dialog;
Then you can easily access the views of the dialog within the callback of the dialog:
dialog.findViewById(R.id.username_edit);
You have to do this because when creating the callback it is in a way constructing a new class in memory so when you call findViewById() directly it can't find the activity
try this code
uetd=(EditText) textEntryView.findViewById(R.id.username_edit);
after following line in your code
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);

Categories

Resources