Updating list fragment with list adapter - android

Currently ran into an issue trying to update a list fragment with a dialogfragment input (or dummy input) everything compiles but don't see any change to the list.
Please let me know what you think. Thanks.
public class NewEventDialogFragment extends DialogFragment {
private List<GlobalClass> mItems;
EditText editText;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//editText = (EditText) findViewById(R.id.editText);
builder.setMessage("What Would You Like to Name the Event?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mItems = new ArrayList<GlobalClass>();
mItems.add(new GlobalClass("Whoiszzzzzzzzzzzzzzthis", "Adsdfdsdomg"));
mItems.add(new GlobalClass("Whodsfzzzzzzzzzzzzzsdfsisthis", "Addsdfdfomg"));
mItems.add(new GlobalClass("Whoisthzzzzzzzzzzzzzzsdfdsfis", "Addosdfsdfmg"));
// Create the adapter to convert the array to views
MainTabsPagerAdapter adapter = new MainTabsPagerAdapter(getActivity(), mItems);
// Attach the adapter to a ListView
adapter.addAll(mItems);
adapter.notifyDataSetChanged();
//setListAdapter(new MainTabsPagerAdapter(getActivity(), mItems));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
View view = getActivity().getLayoutInflater().inflate(R.layout.neweventdialog_fragment, null);
builder.setView(view);
return builder.create();
}
}
private List<GlobalClass> mItems; // ListView items list
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize the items list
mItems = new ArrayList<GlobalClass>();
Resources resources = getResources();
mItems.add(new GlobalClass("Whoisthis", "Adsdfdsdomg"));
mItems.add(new GlobalClass("Whodsfsdfsisthis", "Addsdfdfomg"));
mItems.add(new GlobalClass("Whoisthsdfdsfis", "Addosdfsdfmg"));
// initialize and set the list adapter
setListAdapter(new MainTabsPagerAdapter(getActivity(), mItems));
}

You need to have ListView in your layout R.layout.neweventdialog_fragment and bind this widget to your view in code, then setAdapter on it.
View view = getActivity().getLayoutInflater().inflate(R.layout.neweventdialog_fragment, null);
ListView listView = (ListView) view.findViewById(R.id.listView); // you bind to listView your widget
listView.setAdapter(adapter); // you set adapter
builder.setView(view);
return builder.create();
When you wants to appear DialogFragment, you use NewEventDialogFragment.newInstance().show(getSupportFragmentManager(),CURRENT_FRAGMENT_TAG);

Related

Display more than one item in array list

Hello guys i would like to display more than one item horizontally in a single list. This items are picked from the dialog box that has two button ok and cancel. When you click okay it should pick the values from the edit text and a string value from the dialog and display in the list horizontally.
Array List Adapter
public class VehicleListAdapter extends ArrayAdapter<String> {
private Context context;
private List<String> vehicle_no;
public VehicleListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
this.context = context;
this.vehicle_no = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the vehicle number we are displaying
String my_vehicle = vehicle_no.get(position);
//get the inflater and inflate the XML layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.vehicle_num_layout, null);
TextView txt_vehicle_num = (TextView) view.findViewById(R.id.txt_vehicle_num);
txt_vehicle_num.setText(my_vehicle);
return view;
}
}
Activity with the list
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
if(userInput.getText().toString().trim().length()==0) {
userInput.setError("Vehicle Number Required");
focus.start();
String stime = focus.getText().toString();
}
else {
result.setText(userInput.getText());
ListView list = (ListView) findViewById(R.id.list);
vehicle_list.add(userInput.getText().toString().trim());
VehicleListAdapter listAdapter = new VehicleListAdapter(StartWatch.this, 0, vehicle_list);
list.setAdapter(listAdapter);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
First of all, why you are creating new listview every time when user hit ok of dialog. Remove this line ListView list = (ListView) findViewById(R.id.list); from dialog positive button click.
Add line as shown below after your code in positive button click
VehicleListAdapter listAdapter = new VehicleListAdapter(StartWatch.this, 0, vehicle_list);
list.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged(); // Add this line to tell adapter that data has been changed

How do you delete an Item from a ListView from a dialog box class?

I made my own dialog box class. This class has a button to delete an item from a listview(which is the main acctivity_main.xml). When I push the delete button the item does not get deleted.
I have seen this topic Android: how to remove an item from a listView and arrayAdapter. It just appears the user does not know how to get the item index correctly, which I believe I have done correctly.
Remove ListView items in Android This one is pretty close. But in my code I created my own dialog, this one is using a positive and negative button. I am passing variables between my dialog class and to the mainActivity.
my onClickListener in OnCreate withing the MainActivity
mFoodDataAdapter = new FoodDataAdapter();
final ListView listFoodData = (ListView) findViewById(R.id.listView);
listFoodData.setAdapter(mFoodDataAdapter);
//Handle clicks on the ListView
listFoodData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) {
FoodData tempFoodData = mFoodDataAdapter.getItem(whichItem);
//create a new dialog window
DialogShowFood dialog = new DialogShowFood();
// send in a reference to the note to be shown
dialog.sendFoodDataSelected(tempFoodData);
FoodDataAdapter adapter1 = new FoodDataAdapter();
/*this is where i send the data to the DialogShowFood.java*/
dialog.sendFoodDataAdapter(adapter1, whichItem);
// show the dialog window with the note in it
dialog.show(getFragmentManager(),"");
}
});
Here is my class for the dialog "DialogShowFood.java"
public class DialogShowFood extends DialogFragment {
FoodData mFood;
MainActivity.FoodDataAdapter mAdapter;
int mitemToDelete;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_show_food, null);
Button btnDelete = (Button) dialogView.findViewById(R.id.btnDelete);
builder.setView(dialogView).setMessage("Your food");
/*this sends the item to delete to the adapter*/
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapter.deleteFoodData(mitemToDelete);
dismiss();
}
});
return builder.create();
}
/*this gets the data to delete from the MainActivity*/
public void sendFoodDataAdapter(MainActivity.FoodDataAdapter adapter1, int whichItem) {
mAdapter = adapter1;
mitemToDelete = whichItem;
}
}
The function inside the adapter
/*this is the function in the base adapter to delete the item*/
public void deleteFoodData(int n){
Toast.makeText(MainActivity.this,Integer.toString(n), Toast.LENGTH_SHORT).show();
foodDataList.remove(n);
notifyDataSetChanged();
}
The Toast outputs the proper indexes of the item to delete, it just does not delete the item for some reason.

Android - spinner within dialog won't populate

I'm trying to add a two spinners inside a dialog (popup). The problem I'm having is populating the spinners. I get no error I can see, and basically the same code works if It's in a tab-fragment, and not the dialog.
This is the code that does not popluate the spinners inside the dialog.
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
League league;
league = ((LeagueMainActivity)getActivity()).getLeague();
View v = inflater.inflate(R.layout.diaglog_add_match, null);
Spinner spinner1 = (Spinner) v.findViewById(R.id.spinner_dialog_player1);
Spinner spinner2 = (Spinner) v.findViewById(R.id.spinner_dialog_player2);
String [] items = {"test 1", "test 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("Spinner: ", "" + spinner1);
spinner1.setAdapter(adapter);
spinner2.setAdapter(adapter);
builder.setView(inflater.inflate(R.layout.diaglog_add_match, null))
.setTitle("Add match")
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//LoginDialogFragment.this.getDialog().cancel();
/* do I really need to do anything??? */
}
});
AlertDialog dialog = builder.create();
return dialog;
}
This is the code that works within a (tabbed) fragment:
public class UnnamedFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_unnamed, container, false);
Spinner spinner1 = (Spinner) rootView.findViewById(R.id.spinner);
String [] items = {"test 1", "test 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("Spinner: ", "" + spinner1);
spinner1.setAdapter(adapter);
return rootView;
}
}
Okay so what I did wrong was inflating/creating two independent views with the same context.
First I did:
View v = inflater.inflate(R.layout.diaglog_add_match, null);
And then:
builder.setView(inflater.inflate(R.layout.diaglog_add_match, null))
So I set the view for the builder as a new view, and not the same ones I used for the spinner.
So instead if I do:
View v = inflater.inflate(R.layout.diaglog_add_match, null);
builder.setView(v)
That does the trick.

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.

DragSortListView and AlertDialog?

I have been trying to get this library:
https://github.com/bauerca/drag-sort-listview/
to work inside an AlertDialog. But I have has no success so far. Everything looks perfect but the drag and drop does not happen.
Any suggestion it can be done? If there is no way to do this inside a AlertDialog, is there a way to do this without using intents?
Here is my code:
public class FolderSorter
{
Context parent;
ArrayList<String> lists;
ArrayAdapter<String> adapter;
public FolderSorter(Context context)
{
this.parent = context;
lists = new ArrayList<String>();
adapter = new ArrayAdapter<String>(parent, R.layout.list_item1,
R.id.text1);
}
public void setList(List<String> mlist)
{
this.lists.addAll(mlist);
}
public void doSort()
{
LayoutInflater factory = LayoutInflater.from(parent);
final View lview = factory.inflate(R.layout.sort_folders, null);
AlertDialog.Builder builder = new AlertDialog.Builder(parent);
builder.setTitle("Sort Folders");
builder.setView(lview);
// ListView list = (ListView) lview.findViewById(R.id.listView1);
DragSortListView list2 = (DragSortListView) lview
.findViewById(R.id.dragSortListView1);
adapter.addAll(lists);
// list.setAdapter(adapter);
list2.setAdapter(adapter);
// TODO: set buttons OK and CANCEL
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
}
});
final Dialog dialog = builder.create();
dialog.show();
}
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener()
{
#Override
public void drop(int from, int to)
{
String item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
}
};
private DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener()
{
#Override
public void remove(int which)
{
adapter.remove(adapter.getItem(which));
}
};
}
I had a similar problem when using the DragSortListView inside a dialog fragment - turned out this only happened when the soft keyboard was visible when the fragment was being displayed. I'm not sure what the exact issue is, but I think something is either interfering with the focus or touch events the DragSortListView uses.
As a work around I hide the softkeyboard before displaying the fragment, this appears to solve the issue for now - see the below answer for the code on how to do this:
https://stackoverflow.com/a/7696791/1062909

Categories

Resources