How to delete an Item from a Spinner Using an AlertDialog - java

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

Related

Refresh Listview after a dialog

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

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 !

Apply the notifyDataSetChanged on stored list in sharedpreferences

I have a problem about my listview i am populating my listview with what the user enters in the dialog box when the add new button is clicked. When this button is clicked a dialog appears and asks the user to input something when the user presses done what he/she enters does not appear in the view from the list even when i put the notifyDataSetChanged. What the user inputs only appear when the fragment has been restarted. I think it may involved the saving in sharedpreferences which is the tinyDB in the code. How do i make sure the notifyDataSetChanged is noticed by the list that is stored. Thank you
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_year_two_my_courses_first_semester, container, false);
btnAddNew = (Button)rootView.findViewById(R.id.btnAddNewYearTwoFirstSemester);
btnSave = (Button)rootView.findViewById(R.id.btnSaveAddedSubjectsFirstSemesterYr2);
listView = (ListView)rootView.findViewById(R.id.listViewSubjectsMyCoursesFirstSemesterYr2);
tinyDB = new TinyDB(getContext());
storedList = new ArrayList<>(tinyDB.getListString("storedList1stYr2"));
storedArray = new ArrayList<>();
generalList = new ArrayList<>();
generalList.addAll(storedArray);
generalList.addAll(storedList);
getActivity().setTitle("Year Two");
setHasOptionsMenu(true);
btnAddNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnSave.setVisibility(View.VISIBLE);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext(),R.style.DialogeTheme);
// Setting Dialog Title
alertDialog.setTitle("Add new");
// Setting Dialog Message
String getUsername = tinyDB.getString("Username");
alertDialog.setMessage("Hello "+ getUsername + ", please write the new subject");
final EditText input = new EditText(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setTextColor(Color.parseColor("#f06292"));
alertDialog.setView(input);
alertDialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String getSubjectInput = input.getText().toString();
storedList.add(getSubjectInput);
tinyDB.putListString("storedList1stYr2", storedList);
arrayAdapter.notifyDataSetChanged();
}
});
alertDialog.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.create();
alertDialog.show();
}
});
arrayAdapter = new CustomListAdapter(getContext(),generalList);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
return rootView;
}
Your CustomListAdapter is observing generalList, which does not change when you add a new String in storedList.
You could do this :
public void onClick(DialogInterface dialogInterface, int i) {
String getSubjectInput = input.getText().toString();
storedList.add(getSubjectInput);
tinyDB.putListString("storedList1stYr2", storedList);
generalList.add(getSubjectInput);
arrayAdapter.notifyDataSetChanged();
}
or clear and reset your list.

I Have Crash Error when I Clicked Button; The specified child already has a parent. You must call removeView() on the child's parent first

I have this error:
The specified child already has a parent. You must call removeView()
on the child's parent first.
When I clicked buildNot.setPosiviteButton.
Help me please, thanks guys!
This is my Java source code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
list = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
etDers = new EditText(MainActivity.this);
etNot = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
//Dialog Not
final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
buildNot.setTitle("Not Ekle");
buildNot.setView(etNot);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
dialog.cancel();
}
});
final AlertDialog alertDers = build.create();
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter = (ArrayAdapter ) list.getAdapter();
String item = (String) list.getSelectedItem();
int position = list.getSelectedItemPosition();
item += "YourText";
adapter.insert(item, position);
dialog.cancel();
}
});
final AlertDialog alertNot = buildNot.create();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
alertNot.show();
}
});
list.setAdapter(adapter);
btnDersEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDers.show();
}
});
}
That is because nothing is selected.
list.getSelectedItemPosition() will always return -1.
"Click" and "select" are separate things. "Select" in a ListView is done via the pointing device (D-pad, trackball, arrow keys, etc.).
list.getSelectedItemPosition() will always return -1 if you are not using D-pad, trackball or arrow keys.
You should store the position in onItemClick(AdapterView<?> parent, View view, int position, long id) as a class member and access it in buildNot.setPositiveButton onClick.
Coding below, where mPosition is a class member of your class.
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter = (ArrayAdapter ) list.getAdapter();
String item = (String) adapter.getItem(mPosition);
item += "YourText";
adapter.insert(item, mPosition);
dialog.cancel();
}
});
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mPosition = position;
alertNot.show();
}
});
Try change your code like below, maybe help
public class MainActivity extends ListActivity {
int posmy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainlistnew);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
final ListView list = getListView();
final ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
final EditText etDers = new EditText(MainActivity.this);
final EditText etNot = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
//Dialog Not
final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
buildNot.setTitle("Not Ekle");
buildNot.setView(etNot);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
dialog.cancel();
}
});
final AlertDialog alertDers = build.create();
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//adapter = (ArrayAdapter ) list.getAdapter();
//String item = (String) list.getSelectedItem();
//int position = list.getSelectedItemPosition();
int position=posmy;
String item = "YourText" + etNot.getText().toString();
adapter.insert(item, position);
dialog.cancel();
}
});
final AlertDialog alertNot = buildNot.create();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
posmy=position;
alertNot.show();
}
});
list.setAdapter(adapter);
btnDersEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDers.show();
}
});
}
}

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().

Categories