I have read a many posts on this topic but none is helping.I have a listview and I have a dialog.The dialog contains three Edittext fields one for name,description and date.I have two Buttons on the dialog save and cancel. On clicking the save button , insert the data in database but listview doesn't get updated.
This is the method where I specify the function of the save button :
save_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedModel=new Model();
selectedModel.setTask_title(task_Title.getText().toString());
selectedModel.setTask_description(task_Description.getText().toString());
selectedModel.setTask_date(task_Date.getText().toString());
db.insertTask(selectedModel);
//Toast.makeText(getApplicationContext(),"model ="+selectedModel.getTask_title(),Toast.LENGTH_LONG).show();
dialog.dismiss();
//myAdapter.notifyDataSetChanged();
}
});
I have tried using .notifyDataSetChanged() but it didn't work.
This is my main code where I specify all the functions :
public class SecondScreen extends ListActivity implements AppCompatCallback,AdapterView.OnItemClickListener {
private Toolbar bar;
private AppCompatDelegate delegate;
List<Model> list;
ArrayAdapter<String> myAdapter;
final Context context=this;
Model selectedModel;
AGSQLiteHelper db;
private EditText task_Title,task_Description,task_Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
delegate=AppCompatDelegate.create(this,this);
super.onCreate(savedInstanceState);
delegate.setContentView(R.layout.activity_second_screen);
bar=(Toolbar)findViewById(R.id.toolbarID);
delegate.setSupportActionBar(bar);
ActionBar ab=delegate.getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
db=new AGSQLiteHelper(this);
db.onUpgrade(db.getWritableDatabase(),1,2);
db.createTask(new Model("abcde","description abcde","19/11/12"));
db.createTask(new Model("bcdese","description bcdese","18/12/12"));
db.createTask(new Model("mnbv","description mnbv","2/11/10"));
db.createTask(new Model("poiuy","description poiuy","1/5/6"));
list=db.getAllTasks();
List<String> listTitle=new ArrayList<String>();
for(int i=0;i<list.size();i++){
listTitle.add(i,list.get(i).getTask_title());
}
myAdapter=new ArrayAdapter<String>(this,R.layout.row,R.id.tasktitleTextID,listTitle);
getListView().setOnItemClickListener(this);
setListAdapter(myAdapter);
}
#Override
public void onSupportActionModeStarted(ActionMode mode) {
}
#Override
public void onSupportActionModeFinished(ActionMode mode) {
}
#Nullable
#Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
return null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.add){
Toast.makeText(getApplicationContext(),"Add was clicked",Toast.LENGTH_LONG).show();
final Dialog dialog=new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Dialog");
Button save_button=(Button)dialog.findViewById(R.id.saveButtonID);
Button cancel_button=(Button)dialog.findViewById(R.id.cancelButtonID);
task_Title=(EditText)dialog.findViewById(R.id.titleEditTextID);
task_Description=(EditText)dialog.findViewById(R.id.descriptionEditTextID);
task_Date=(EditText)dialog.findViewById(R.id.dateEditTextID);
dialog.show();
save_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedModel=new Model();
selectedModel.setTask_title(task_Title.getText().toString());
selectedModel.setTask_description(task_Description.getText().toString());
selectedModel.setTask_date(task_Date.getText().toString());
db.insertTask(selectedModel);
//Toast.makeText(getApplicationContext(),"model ="+selectedModel.getTask_title(),Toast.LENGTH_LONG).show();
dialog.dismiss();
//myAdapter.notifyDataSetChanged();
}
});
cancel_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
if(item.getItemId()==R.id.done){
Toast.makeText(getApplicationContext(),"Done was clicked",Toast.LENGTH_LONG).show();
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
}
Any suggestions?
you need to add the new entry into the listTitle used by the adapter
db.insertTask(selectedModel);
dialog.dismiss();
listTitle.add(selectedModel.getTask_title());
myAdapter.notifyDataSetChanged();
so make your listTitle global to the class so that you can use it inside other functions
public class SecondScreen extends ListActivity...{
private EditText task_Title;
private List<String> listTitle;
// declare list like this as global to class
... onCreate(..){
listTitle=new ArrayList<String>();
}
}
Related
I am trying to create a listener of a button of a customdialog which extends DialogFragment class and I want to locate the listener of custom buttons out of customdialog fragment class .However when I try to call the view of CustomDialog Fragment then I am getting null exception. What I do is to create an new instance of the customdialog fragment in somewhere else and say
customdialog.getView().findViewById(R.id.custombutton);
but I am getting null.
public class CustomDialog extends DialogFragment {
public final int RES_NONE = -1;
private TextViewCustomFont dialogTitle, view2, dialogBodyBottom,
dialogBodyTop;
private EditTextCustomFont dialogEditText;
private ButtonCustomFont dialogLeftButton;
private ButtonCustomFont dialogRightButton;
private Typeface GothamBold, GothamMedium, GothamUltra;
private static int title1, bodyTop1, bodyBottom1, EditTextHint1,
leftButton1, rightButton1;
onSubmitListener mListener;
private Dialog dialog;
interface onSubmitListener {
void setOnSubmitListener(String arg);
}
public static CustomDialog newInstance(int title, int bodyTop,
int bodyBottom, int EditTextHint, int leftButton, int rightButton) {
title1 = title;
bodyTop1 = bodyTop;
bodyBottom1 = bodyBottom;
EditTextHint1 = EditTextHint;
leftButton1 = leftButton;
rightButton1 = rightButton;
CustomDialog frag = new CustomDialog();
return frag;
}
public ButtonCustomFont getDialogLeftButton() {
return dialogLeftButton;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dialog = new Dialog(getActivity());
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
//dialog.setContentView(R.layout.dialog_layout);
//dialog.show();
initLayout();
return dialog;
}
private void initLayout(){
dialog.setContentView(R.layout.dialog_layout);
setDialogView();
setCustomDialog();
}
public void setDialogView(){
//Create an java object of each dialog view item
dialogTitle = (TextViewCustomFont) dialog.findViewById(R.id.custom_dialog_title);
dialogBodyTop = (TextViewCustomFont) dialog.findViewById(R.id.custom_dialog_body_top);
dialogBodyBottom = (TextViewCustomFont) dialog.findViewById(R.id.custom_dialog_body_bottom);
dialogEditText = (EditTextCustomFont) dialog.findViewById(R.id.custom_dialog_body_et);
dialogLeftButton = (ButtonCustomFont) dialog.findViewById(R.id.custom_dialog_body_btn_left);
dialogRightButton = (ButtonCustomFont) }
public class LoginSelectionFragment extends Fragment {
public static LoginSelectionFragment newInstance() {
LoginSelectionFragment fragment = new LoginSelectionFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_loginselection,
container, false);
}
I am trying to pull the dialogLeftButton of CustomDialog Fragment and assing a listener on it inside the LoginSelectionFragment.
Here is how it looks like after I added method 2. This a part of LoginSelectionFragment
private void TwoButtonTextEditTextDialog(){
String title = getResources().getString(R.string.invalid_info_header);
String body = getResources().getString(R.string.invalid_info_body);
String body2 = getResources().getString(R.string.hint_newemail);
String btn1 = getResources().getString(R.string.cancel_uppercase);
String btn2 = getResources().getString(R.string.ok_alert);
fragmentDialog = CustomDialog.newInstance(title, body, body2, RES_NONE, btn1, btn2);
fragmentDialog.setCustomDialogFragmentListener(mDialogClickListener);
fragmentDialog.show(getFragmentManager(), "");
}
private CustomDialog.CustomDialogFragmentListener mDialogClickListener = new CustomDialog.CustomDialogFragmentListener(){
#Override
public void onNegativeClick() {
// TODO Auto-generated method stub
fragmentDialog.dismiss();
}
#Override
public void onPositiveClick() {
// TODO Auto-generated method stub
fragmentDialog.dismiss();
}
};
#Override
public void onNegativeClick() {
// TODO Auto-generated method stub
}
#Override
public void onPositiveClick() {
// TODO Auto-generated method stub
}
You could create a method as setDialogButtonClickListener(CustomDialog.OnButtonClickListener clickListener); where CustomDialog.OnButtonClickListener is an inner static interface , that way you could listen to click events of the buttons from anywhere.
An example of this could look as below,
public class CustomDialog extends DialogFragment {
.....
public static CustomDialog newInstance(int title, int bodyTop,
int bodyBottom, int EditTextHint, int leftButton, int rightButton) {
CustomDialog frag = new CustomDialog();
Bundle args = new Bundle();
args.putInt("title", title);
......
frag.setArguments(args);
return frag;
}
...
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(title)
.setPositiveButton(android.R.string.ok, this)
.setNegativeButton(android.R.string.cancel, this)
....
.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
listener.onRightButtonClick();
default:
listener.onLeftButtonClick();
}
}
}
...
private CustomDialog.OnButtonClickListener mClickListener;
....
public void setDialogButtonClickListener(CustomDialog.OnButtonClickListener clickListener){
mClickListener = clickListener;
}
...
public static interface OnButtonClickListener {
public void onLeftButtonClick();
public void onRightButtonClick();
}
}
If you notice from the above sample I posted , I have besides solving your problem of setting the click listener on buttons also have introduced you with the Factory Design Pattern on Android , You can see that instead of creating static fields for the button title and Dialog title I've set them in the Bundle Argument and then Retrieve them in the Dialogs onCreate() method.
For more Best Practices of Fragment You can take a look here
Edit
Ok , for your help I am providing you a Glimpse of what your LoginSelectionFragment should look like.
public class LoginSelectionFragment extends Fragment implements CustomDialog.OnButtonClickListener {
......// Method 1
public void showDialog(String title , String message .....) {
CustomDialog dialog = CustomDialog.getInstance(title , message...);
dialog.setDialogButtonClickListener(this);
dialog.show(getSupportFragmentManager(), null);
}
public void onLeftButtonClick(){
...// do something on left button click of dialog
}
public void onRightButtonClick(){
// do something on right button click of dialog
..
}
// Method 2
public void showDialog2(String title , String message .....) {
CustomDialog dialog = CustomDialog.getInstance(title , message...);
dialog.setDialogButtonClickListener(mDialogClickListener);
dialog.show(getSupportFragmentManager(), null);
}
private final CustomDialog.OnButtonClickListener mDialogClickListener = new CustomDialog.OnButtonClickListener() {
public void onLeftButtonClick(){
...// do something on left button click of dialog
}
public void onRightButtonClick(){
// do something on right button click of dialog
..
}
}
}
Now If you look at Method 1 , we have given parameters to showDialog() method so that you could reuse it for showing multiple times with different arguments ie., you could use this approach when you want to show the same dialog with different title , message etc
and in Method 2 we have provided an anonymous inner class for handling click events you could as many anonymous inner classes as you have different varieties of dialog ie dialog with different UI and different Event listeners in the same activity/fragment.
Enjoy!
Try to use this, (did not test this)
public class MyDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.input_warning)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
return builder.create();
}
}
and in your Activity fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.workout_a_fragment, container, false);
Button button = (Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
MyDialogFragment dialog = new MyDialogFragment();
dialog.show(fm, DIALOG_WARNING);
}
});}
In Code 2, I use final ListView lv=this.getListView() to get ListView object, it's OK.
In Code 1, I try to use ListView lv=((ListActivity)getApplicationContext()).getListView() to get ListView object, but it's bad.
Is there a simple way to get get ListView object in setOnClickListener? Thanks
Code 1
private void IniControl(){
findViewById(R.id.btnCancel).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ListView lv=((ListActivity)getApplicationContext()).getListView();
for(int i=0;i<lv.getCount();i++){
EditText number = (EditText)lv.findViewWithTag("editNumber"+i);
Toast.makeText(getApplicationContext(),number.getText().toString()+"CW",Toast.LENGTH_SHORT).show();
}
}
});
}
Code 2
public class StepList extends ListActivity{
private ListNumberAdapter mListNumberAdapter=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_step_list);
}
private void IniControl(){
final ListView lv=this.getListView();
findViewById(R.id.btnCancel).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<lv.getCount();i++){
EditText number = (EditText)lv.findViewWithTag("editNumber"+i);
Toast.makeText(getApplicationContext(),number.getText().toString()+"CW",Toast.LENGTH_SHORT).show();
}
}
});
}
}
Is IniControl also a method of StepList in your Code 1 ?
If so, you can simply call getListView() from there (the OnClickListener being an inner class of your StepList), or more explicitely StepList.this.getListView().
The ListView is not a member of the ApplicationContext. Why cant you add the ListView as a member of the Activity instead? Or use the getListView() on the ListActivity's context.
You can write separate OnClickListener method and pass ListView to it.
private View.OnClickListener onClick(final ListView lv) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
}
};
}
You can use onListItemClick Method
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "hoohoo..you clicked me at " + position,Toast.LENGTH_SHORT).show();
}
It will display the the row number you clicked
Make your ListView a class member Variable
private ListView mListView;
Then in onCreate(), call mListView = (ListView) this.getListView();
And then you can use the mListView object anywhere in the rest of the code.
I am using Sliding menu from library jfeinstein, i have two sliding menu 'menuLeft' 'menuRight' in my activity one from left side and one from right,i have toggle buttons for respective sliding menu,how ever if menuLeft is open and if i slide from right to left in order to close menuLeft ,menuRiht also gets opened,what can be the solution to avoid this misbehaviour
here's my activity which contains SlidingMenu's
public class ChatListActivity extends SherlockActivity {
private SlidingMenu menuLeft;
private SlidingMenu menuRight;
private Button btnSliderLeftToggle;
private Button btnSliderRightToggle;
private ListView lvSliderLeft;
private ListView lvSliderRight;
private int width;
private int height;
private DBContacts db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.chatlist_layout);
db = new DBContacts(this);
WindowManager wmanager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = wmanager.getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
menuLeft = new SlidingMenu(this);
menuRight = new SlidingMenu(this);
initLeftSlider();
initRightSlider();
btnSliderLeftToggle = (Button) findViewById(R.id.mnuSlidingleftToggle);
btnSliderLeftToggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
ChatListActivity.this.menuLeft.toggle();
}
});
btnSliderRightToggle = (Button) findViewById(R.id.mnuSlidingRightToggle);
btnSliderRightToggle.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
ChatListActivity.this.menuRight.toggle();
}
});
menuLeft.setOnOpenedListener(new OnOpenedListener()
{
#Override
public void onOpened()
{
lvSliderLeft = (ListView) findViewById(R.id.lvSlidingmenuLeft);
MySLidingMenuLeftAdapter adapter = new MySLidingMenuLeftAdapter(ChatListActivity.this,
R.layout.crow_listview_lvslidingleft_chatlist);
lvSliderLeft.setAdapter(adapter);
}
});
menuRight.setOnOpenedListener(new OnOpenedListener()
{
#Override
public void onOpened()
{
lvSliderRight = (ListView) findViewById(R.id.lvSlidingmenuRight);
String column[] = new String[] { DBContacts.USERNAME};
int[] viewId = { R.id.txtContactName};
Cursor dataBaseCursor = db.getAllContacts();
MySLidingMenuRightAdapter customContactListAdapter = new MySLidingMenuRightAdapter(
ChatListActivity.this, R.layout.crow_lvslidingmenu_right_chatlist, dataBaseCursor, column,
viewId, 0);
lvSliderRight.setAdapter(customContactListAdapter);
}
});
}
private void initRightSlider()
{
menuRight.setMode(SlidingMenu.RIGHT);
menuRight.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menuRight.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menuRight.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menuRight.setMenu(R.layout.sliding_menu_chatlist_right);
menuRight.setFadeDegree(0.35f);
}
private void initLeftSlider()
{
menuLeft.setMode(SlidingMenu.LEFT);
menuLeft.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menuLeft.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menuLeft.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menuLeft.setMenu(R.layout.sliding_menu_chatlist_left);
menuLeft.setFadeDegree(0.35f);
}
#Override
public void onBackPressed()
{
super.onBackPressed();
System.exit(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add("Refresh");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
new SendNativeContacts(this).execute();
return true;
}
}
I have never faced this issue when i used both Left and Right SlidingMenu but for your problem you can have look at SlidingMenu Issues and you can try this solution for your problem. It may help you.
EDIT :
try this
You will need a patch which calls onOpened and onClosed methods for right menu it may have been included in latest code. Write logs to check method calls.
slidingMenuLeft.setOnOpenedListener(new OnOpenedListener() {
#Override
public void onOpened(int pos) {
slidingMenuRight.setSlidingEnabled(false);
}
});
slidingMenuLeft.setOnClosedListener(new OnClosedListener() {
#Override
public void onClosed() {
slidingMenuRight.setSlidingEnabled(true);
}
});
slidingMenuRight.setOnOpenedListener(new OnOpenedListener() {
#Override
public void onOpened(int pos) {
slidingMenuLeft.setSlidingEnabled(false);
}
});
slidingMenuRight.setOnClosedListener(new OnClosedListener() {
#Override
public void onClosed() {
slidingMenuLeft.setSlidingEnabled(true);
}
});
I have one ListFragment called MeasurementList which displays all registered measurement data. To register new measurement data Im using DialogFragment named NewMeasurement with custom made view in AlertDialog with required UI controls to be filled out.
Now, I need an elegant solution to update the measurement list in the ListFragment with the new registered measurement after the DialogFragment is dismissed. I don't want to update the list from the database, but rather just adding the newly created Measurement object to the list. I have tried to follow Android guidelines on how to make fragments communicate with activities through callback interfaces (Creating event callbacks to the activity). The MeasurementList passes its reference to the NewMeasurement so it can call it back after registering new measurement. The problem is how to save the listener reference in the Bundle in the NewMeasurement.newInstance() method. It mainly saved the primitive data types and not objects like in my case.
Any tip and suggestions would be appreciated.
MeasurementList.java
public class MeasurementList extends ListFragment implements OnMeasurementSetListener {
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addMeasurement:
NewMeasurement newMeasurementDialog = NewMeasurement.newInstance(this);
newMeasurementDialog.show(getFragmentManager(), "newMeasurementDialog");
break;
default:
break;
}
return true;
}
#Override
public void onMeasurementSet(Measurement measurement) {
MeasurementAdapter listAdapter = (MeasurementAdapter) getListAdapter();
listAdapter.add(measurement);
}
}
OnMeasurementSetListener.java
public interface OnMeasurementSetListener {
public abstract void onMeasurementSet(Measurement measurement);
}
NewMeasurement.java
public class NewMeasurement extends DialogFragment
{
private OnMeasurementSetListener mListener;
public static NewMeasurement newInstance(OnMeasurementSetListener listener)
{
NewMeasurement nm = new NewMeasurement();
Bundle b = new Bundle();
b.putSerializable("listener", listener); // NOT WORKING
f.setArguments(b);
return f;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final View v = factory.inflate(R.layout.layout_dialog_new_measurement, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.title_alert_dialog_new_weight);
builder.setIconAttribute(R.drawable.add);
builder.setView(v);
builder.setPositiveButton(R.string.alert_dialog_ok, this);
builder.setNegativeButton(R.string.alert_dialog_cancel, this);
return builder.create();
if (savedInstanceState != null)
mListener = (OnMeasurementSetListener) savedInstanceState.getSerializable("listener");
}
}
Hi you can try to handle this onAttach method by setting new measurement it will create a call back to your activity.
public class MeasurementList extends ListFragment implements OnMeasurementSetListener {
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addMeasurement:
NewMeasurement newMeasurementDialog = NewMeasurement.newInstance(this);
newMeasurementDialog.show(getFragmentManager(), "newMeasurementDialog");
break;
default:
break;
}
return true;
}
#Override
public void onMeasurementSet(Measurement measurement) {
MeasurementAdapter listAdapter = (MeasurementAdapter) getListAdapter();
listAdapter.add(measurement);
}
}
NewMeasurement.java
public class NewMeasurement extends DialogFragment {
public interface OnMeasurementSetListener {
public abstract void onMeasurementSet(Measurement measurement);
}
private OnMeasurementSetListener onMeasurementSetListener;
private Measurement currentMeasurement;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
Measurement measurement = new Measurement();
measurement.s = "fragment";
onMeasurementSetListener = (OnMeasurementSetListener) activity;
setMeasurement(measurement);
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement onMeasurementSetListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Fragment Dialog");
builder.setIconAttribute(R.drawable.ic_launcher);
builder.setPositiveButton(R.string.app_name, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.setNegativeButton(R.string.app_name, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
return builder.create();
}
private void setMeasurement(Measurement measurement) {
currentMeasurement = measurement;
onMeasurementSetListener.onMeasurementSet(measurement);
}
}
Sample Measurement.java
public class Measurement {
public String s;
}
Simply said, from your DialogFragment, you can call back to the Activity that contains your ListFragment, calling a newly created method, within the Activity that updates your ListFragment.
I am trying to use a spinner control that will enable the user to delete any list element.
I have an 'add' button to add elements to the list, and a 'delete' button that removes the currently-displayed item from the list.
It works as expected except when the user deletes the last item in the list. At that point, all of the list's items are deleted.
My code is as follows:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// grab our UI elements so we can manipulate them (for the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
// create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
((ArrayAdapter)m_adapterForSpinner).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
// add listener for addButton
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
clearButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
// add listener for addButton
private void addNewSpinnerItem() {
if (m_addItemText.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "The textView is empty", Toast.LENGTH_LONG).show();
} else {
CharSequence textHolder = "" + m_addItemText.getText();
((ArrayAdapter) m_adapterForSpinner).add(textHolder);
}
m_addItemText.setText("");
}
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO
}
});
}
Does anyone have any ideas or suggestions on how to make this work?
The problem with your code is that the deletion is inside the onItemSelected callback, which gets called every time you are deleting an entry, thus deleting recursively until you effectively do not have any more entries to select. If you add a log inside that method:
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
you will see what I mean. I'm sure you can come up with more elegant code, but a quick and dirty hack is to set up a boolean flag to stop the recursion after the first deletion. See the snippet below and add the commented lines to your own code:
public class SpinnerTest extends Activity {
Spinner m_myDynamicSpinner;
EditText m_addItemText;
ArrayAdapter m_adapterForSpinner;
public static boolean cleared = false; // <--- set up a static boolean here
#Override
public void onCreate(Bundle savedInstanceState) {
// all your code unchanged
clearButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
cleared=false; // <--- nope, we did not clear the value yet
clearSpinnerItems();
}
});
}
// code unchanged
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
if (!cleared) // <--- did I do it already?
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
cleared=true; // I did it!
}
// code unchanged
i cann't understand your question.any way you can get the position of the selected item by using getSelectedItemPosition() method.