Refresh Listview after a dialog - java

I'm trying to create a Listview which refresh itself as soon as I press a certain button in my alert dialog. This is my code, which correctly loads the item as soon as I open the activity, but when I click on the negative button of the dialog it successfully does the operation inside it, but does not refresh the list. This is the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
user = loadUser();
final ArrayAdapter<String> arAd = new ArrayAdapter<String>(this, R.layout.user_list,user);
setListAdapter(arAd);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
new AlertDialog.Builder(UserList.this)
.setTitle("Gestisci test")
.setMessage("Scegli un'operazione")
.setPositiveButton("Apri test", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//to handle
}
})
.setNegativeButton("Elimina Test", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
File dir = new File("..");
dir.delete();
//Here I should refresh the list
arAd.notifyDataSetChanged();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
}

You should remove the item from the adapter after or before deleting the file and call notifyDataSetChanged(), removing a file from the file system and calling notifyDataSetChanged() on the adapter won't refresh the list in the adapter

Related

requestFeature() must be called before adding content - RecyclerView

Im trying to bulid a clickable RecyclerView that will open a dialog.
I cant figure out what wrong with my code, after I click the RV item the app carsh and this Eror is in the logcat:
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
at com.android.internal.policy.PhoneWindow.requestFeature(PhoneWindow.java:317)
at com.android.internal.app.AlertController.installContent(AlertController.java:231)
at android.app.AlertDialog.onCreate(AlertDialog.java:423)
The Adapter is suppose to create the CustomDialog when the user clicks an item from the RV.
This is my Adapter relevant method:
#Override
public void onBindViewHolder(PartyViewHolder holder, final int position) {
SingleParty party=partyList.get(position);
String partyItemTitle= party.getPartyTitle()+ " at "+ party.getFourDigitTime()+ " in "+ party.getPlace();
holder.partyDescription.setText(partyItemTitle);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((PartiesActivity)context).showCustomDialog(partyList.get(position),position,partyList);
}
});
}
CustomDialog relevant code:
public class CustomDialog extends AppCompatDialogFragment {
private SingleParty editedParty;
private CustomDialogListener listener;
private RadioGroup eventPosted;
private RadioButton published,notPublished;
private EditText minAge, fourDigitTime, customerCost, originalCustomerCost, ticketsLeft, maxTickets, partyTitle, place, partyId, accountId, description;
private boolean selectedB,deleteB;
private String minAgeS, fourDigitTimeS, customerCostS, originalCustomerCostS, ticketsLeftS, maxTicketsS, partyTitleS, placeS, partyIdS, accountIdS, descriptionS;
ToggleButton deleteTB;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
final View view = inflater.inflate(R.layout.custom_dialog, null);
initializeVariables(view);
builder.setView(view)
.setTitle(R.string.dialog_title)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
selectedB=published.isChecked();
getStringDataFromDialog();
listener.applyTexts(selectedB,
deleteB,
minAgeS,
fourDigitTimeS,
customerCostS,
originalCustomerCostS,
ticketsLeftS,
maxTicketsS,
partyTitleS,
placeS,
partyIdS,
accountIdS,
descriptionS);
}
})
// Add action buttons
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//dont save changes
}
});
AlertDialog alertDialog = builder.create();
//gets the dialog to be rtl
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
alertDialog.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
return alertDialog;
}
showCustomDialog:
public void showCustomDialog(SingleParty editedParty, int position, ArrayList<SingleParty> listEdited){
CustomDialog customDialog=new CustomDialog();
customDialog.setEditedParty(editedParty);
//check if he is super admin
//super admin- delete waiting for published and edit/delete published one
this.editedParty=editedParty;
this.editedPosition=position;
this.listEdited=listEdited;
customDialog.show(getSupportFragmentManager(),"");
// customDialog.setDialogValues();
}
Thanks !

How To set a Dialog Box on clicking a Gridview item?

I am new to android. I want to have a dialog box with positive and negative buttons when i click on a gridview item. Right now when i click on an item, it populates another activity with the information of the item that i clicked on.
For example, using putExtra and getExtras , populating the activity works great. Now all i want is that instead of the action being performed on gridView click, i want the action being performed on the ok button of the Alertdialog box.
How should i set the gridview.setOnCLickListener so that it pops up an alertDialog Box when an item is clicked??
gridView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
gridView.setClickable(true);
item= (Hotel) parent.getItemAtPosition(position);
String names = item.getName();
Intent i=new
Intent(HotelList.this,UserViewActivity.class);
i.putExtra("names",names);
startActivity(i);
}
});
Try out the following code:
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
item= (Hotel) parent.getItemAtPosition(position);
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setCancelable(false);
dialog.setTitle("Your Title");
dialog.setMessage("Your Message" );
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String names = item.getName();
Intent i= new Intent(HotelList.this,UserViewActivity.class);
i.putExtra("names",names);
startActivity(i);
alert.cancel();
}
})
.setNegativeButton("Cancel ", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
alert.cancel();
}
});
final AlertDialog alert = dialog.create();
alert.show();
}
});
Hope this helps.
First, remove gridView.setClickable(true). It's simply not necessary. Second, You can create the Dialog in your code:
AlertDialog ad = new AlertDialog.Builder(this).setContentView(R.layout.activity_dialog).show();

How to delete an Item from a Spinner Using an AlertDialog

I'm trying to make an Activity that deletes the item pressed on the Spinner using an AlertDialog. I'm not deleting anything yet, I just added a Toast to make sure it will work.
This is my code:
public class SpinnerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
final Context context = getApplicationContext();
// Create an ArrayAdapter using the string array and a default spinner layout
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int selectionCurrent = spinner.getSelectedItemPosition();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (selectionCurrent != position) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle(R.string.dialogtitle);
//set dialog message
alertDialogBuilder.setMessage(R.string.dialogtext).setCancelable(false)
.setPositiveButton(R.string.si,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked,
Toast.makeText(context, "Eliminar", Toast.LENGTH_SHORT).show();
}
}) .setNegativeButton(R.string.no
, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, do nothing
dialog.cancel();
}
});
alertDialogBuilder.setView(spinner);
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
selectionCurrent = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
When I run the code, the following error is displayed: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
I tried to use ((ViewGroup)spinner.getParent()).removeView(spinner); before the alertDialog.show(); but it still not working.
It says: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Anyone knows how to solve the problem?
First create a variable to inflate the ArrayAdapter:
String[] mTestArray;
Get the data from resources:
mTestArray = getResources().getStringArray(R.array.planets_array);
Inflate the ArrayAdapter with this array:
final ArrayList<String> list =new ArrayList<String>(Arrays.asList(mTestArray));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, list);
And finally remove it in your dialog:
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
mTestArray , android.R.layout.simple_spinner_item);
String item = list.get(position);
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (selectionCurrent != position) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle(R.string.dialogtitle);
//set dialog message
alertDialogBuilder.setMessage(R.string.dialogtext).setCancelable(false)
.setPositiveButton(R.string.si,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
list.remove(position);
adapter.notifyDataSetChanged();
// if this button is clicked,
Toast.makeText(context, "Eliminar", Toast.LENGTH_SHORT).show();
}
}) .setNegativeButton(R.string.no
, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, do nothing
dialog.cancel();
}
});
alertDialogBuilder.setView(spinner);
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
selectionCurrent = position;
}

Returning information from an AlertDialog in Android

I have created the following AlertDialog. In it, the user selects an item from a range of options stored in an XML file and handled using an Adapter, and then clicks either the positive button or the negative button. Here is the code:
public void OpenDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle("Promotion Options");
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(activity.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(com.zlaporta.chessgame.R.layout.promotion, null);
dialog.setView(v);
dialog.setPositiveButton("Choose", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 1) {
System.out.println("ok");
}
}
});
dialog.setNegativeButton("Undo Move", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
Spinner spinner = (Spinner) v.findViewById(com.zlaporta.chessgame.R.id.promotionSpin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(activity, com.zlaporta.chessgame.R.array.option,
android.R.layout.simple_spinner_item);
//could be other options here instead of simple_spinner_dropdown_item. Just type simple and see what comes up next time
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Now, I'd like information about the user's selection in the spinner to be passed back to the enclosing Activity after the positive button is clicked. What's the best way to do this?
As you seem to have defined the AlertDialog in a separate class, you cannot directly access methods defined inside the Activity from where it is invoked.
One possible way is to define a public method inside the Activity as follows:
public void doSomething(Object spinnerDataObject){
....
}
and access it this way:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// call the Activity's method here and send the selected item.
((MainActivity)activity).doSomething(parent.getItemAtPosition(position));
dialog.dismiss();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
This will send the selected Spinner data object to the Activity. Whatever you want to do with that object can be done inside doSomething().

Get User Selection in Alert Dialog

I have a button inside a popupwindow that when clicked initializes an alertdialog with a list from which the user can choose from. I'm stuck trying to get the string value of the selected item from the list. I'm trying to get the item and then change the description text on the button to reflect the user's selection.
countryButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//String countryResult = countryList.get(which);
//countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});
You have to use ArrayAdapter.getItem() method. And if it isn´t just a copy paste mistake, don´t forget the #Override annotation. But what do You mean with "missing reference error"?
countryButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String countryResult = countryAdapter.getItem(which);//use this getItem() method
countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});

Categories