How to create a alert dialog box when back button is pressed? - java

I want to show a alert dialog box to the user when the back button is pressed..For example :Are you sure want to exit ?.I am not having a problem in creating a alert dialog box..I am having a problem in where to call this dialog box method().
This is my HomeScreen.java
public class HomeScreen extends TabActivity {
ConferenceOpenHelper helper_ob;
Cursor cursorHome;
ProfileEditScreen profileEditScreen;
ConferenceAdapter adapter;
EcMeeting meeting;
final Context context = this;
public static int HOMETEMP = 1;// Constant for Deleting the last created id
// in edit profile screen (Cancel)
public static String HOME = "home";// constant for updating status column
public static String CUSTOM_DIALER = "custom";
public static String TEMPLATE = "template";// constant for updating status // column
public static TabHost tabHost;
public static final int QUICK_START = 1;// Constant for menu options
public static final int TEMPLATE_SCREEN = 2;// Constant for menu options
public static final int USER_GUIDE = 3;// Constant for menu options
public static final int QUICK_CALL = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
Resources ressources = getResources();
tabHost = getTabHost();
// Android tab
Intent photo = new Intent().setClass(this,EcMeeting.class);
TabSpec tabSpecphoto = tabHost
.newTabSpec("Calendar")
.setIndicator("Calendar", ressources.getDrawable(R.drawable.calendartab))
.setContent(photo);
// Apple tab
Intent intentApple = new Intent().setClass(this,CallListScreen.class);
TabSpec tabSpecApple = tabHost
.newTabSpec("Calls")
.setIndicator("Calls", ressources.getDrawable(R.drawable.ic_action_device_access_call))
.setContent(intentApple);
// Windows tab
Intent intentWindows = new Intent().setClass(this,UserSettingActivity.class);
TabSpec tabSpecWindows = tabHost
.newTabSpec("Settings")
.setIndicator("Settings", ressources.getDrawable(R.drawable.ic_action_setting))
.setContent(intentWindows);
// add all tabs
tabHost.addTab(tabSpecphoto);
tabHost.addTab(tabSpecApple);
tabHost.addTab(tabSpecWindows);
//set Windows tab as default (zero based)
/*tabHost.setCurrentTab(0);*/
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#d3d3d3"));
}
tabHost.getTabWidget().setCurrentTab(0);
/*tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#C35817"));*/
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, QUICK_START, 0, "Quick Start").setIcon(R.drawable.ic_menu_add_icon);
menu.add(0, USER_GUIDE, 0, "User Guide").setIcon(R.drawable.ic_menu_guide_icon);
return true;
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case QUICK_START:
startActivity(new Intent(this, ConfDialerScreen.class));
break;
case USER_GUIDE:
startActivity(new Intent(this, UserGuideScreen.class));
break;
}
return true;
}
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#8A4117"));
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#C35817"));
}
}
This is the method() to create alert dialog
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
Now ,I really did not know where to call this method.Could someone give any Idea?
when user press the back button I want to show the alert Dialog.

Try below code:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialogOnBackPress();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void dialogOnBackPress() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}

Use this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert Message:");
builder.setMessage("Do you want to save this image to your file??");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// do your stuff
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
return super.onKeyDown(keyCode, event);
}

you can this code modify acc. to req.
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
dialog.dismiss();
}
return true;
}
});

do not call super.onBackPressed(); in onBackPressed

Else you can simply add onBackPressed() in activity_main.xml(tab.xml) as
android:onClick="onBackPressed"
mention it in your button properties

Related

Returning checked items from multi-choice dialog

By reading the documentation, I have managed to create a multiple choice dialog box. However, there's one bit that still has me completely stumped. When the user clicks "Okay", how do I return them to the parent Activity?
I"m referring to this particular comment:
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
...
}
How exactly would I 'return them to the component that opened the dialog'?
My dialog call in my activity:
public void chooseTeam(View v) {;
DialogFragment newDialog = MultiChoiceDialog.newInstance(teamNamesArray);
newDialog.show(getFragmentManager(), "Choose_team");
}
and my dialog code:
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] team = getArguments().getStringArray("team");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.choose_team).setMultiChoiceItems(team, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
list.add(team[which]);
} else if (list.contains(team[which])) {
list.remove(team[which]);
}
}
}).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selections = "";
for (String ms : list) {
selections = selections + "\n" + ms;
}
Toast.makeText(getActivity(), "Team Selected: " + selections,
Toast.LENGTH_LONG).show();
AddTaskActivity.chosenTeam = list;
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Toast.makeText(getActivity(), "Cancelled.", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
You can make the ArrayList a class member variable like private ArrayList mSelectedItems;
See example code below
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList mSelectedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
// in this case the OK button has more or less no function but if want save the check options in database or shared preference, you can put your code here. So it depends on your use case.
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}
}

Hide AlertDialog in specific activity

I have one Quote application. When I open the application's MainActivity, if there is new data updated on the server side, one AlertDialog is shown for going to SettingsActivity. It takes some time for appear so if the app is already on SettingsActivity, it is still showing the AlertDialog to go to SettingsActivity.
I want to prevent the AlertDialog from showing in SettingsActivity but continue showing in other activities. My code for AlertDialog is below. How can I do that?
public class UpdatesDialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(UpdatesDialogActivity.this);
builder.setTitle("Download New Status");
builder.setMessage("There Are New Status Arrived. Push Download Button From Settings.");
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(UpdatesDialogActivity.this, SettingsActivity.class);
finish();
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
finish();
return false;
}
});
builder.show();
}
// ==============================================================================
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
You can go for an 'instanceof' check and see if the current activity is settings or else.
if(activity instanceof SettingsActivity){
//don;t show dialog
}else{
//show dialog
}
Hope this will help.

Calling AlertDialog.Builder in Java For Android Fragment When Back Button Is Pressed

I have a simple application (really!) that displays a list and then displays the details of an item on the list based on the user's choice. I do this using Fragments. The details portion is a Fragment which has an EditText in it. Currently, if the user types in the EditText and clicks on the Save button, an AlertDialog.Builder pops up asking her if she wants to save. If she chooses yes, the text is saved to a database. I want the same thing to happen if the user hits the back button. In my class that extends FragmentActivity, I have:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
super.onKeyDown(keyCode, event);
DetailFrag frag = (DetailFrag) getSupportFragmentManager().findFragmentById(R.id.frag_stitchdetail);
frag.onKeyDown(keyCode, event);
return false;
}
In my class that extends Fragment (the details portion), I have:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getRepeatCount() == 0
&& Edited) {
return true;
}
else
return false;
}
I'm not sure where to put the code that will call the AlertDialog.Builder. I want to put it in the Fragment class because the code needs to get the rowID of the detail from the list (a class that extends ListFragment). That information isn't available to the FragmentActivity class. For clarification, here's the code I use to operate the Save button. It's called from the onCreateView method of the Fragment class and I want to re-use this code (put it in its own method, probably) when the back button is hit.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detailfragment, container, false);
Typeface danielFont = Typeface.createFromAsset(getActivity().getAssets(),
"danielbk.ttf");
final EditText notes = (EditText)view.findViewById(R.id.stitchnotes);
notes.setTypeface(danielFont);
notes.setTextSize(12);
builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Do you want to save your Notes?");
builder.setCancelable(false);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String Notes = notes.getText().toString();
Uri updateUri = ContentUris.withAppendedId(STITCHES_URI, rowID);
ContentValues values = new ContentValues();
values.put("stitchnotes", Notes);
getActivity().getContentResolver().update(updateUri,values,null,null);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
//getActivity().finish();
}
});
alert = builder.create();
ImageButton savebutton = (ImageButton)view.findViewById(R.id.savebutton);
savebutton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
alert.show();
}
});
notes.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
Edited = true;
}
});
return view;
}
The rowID that's used when I declare updateURI comes from the ListFragment class like so:
DetailFrag frag = (DetailFrag) getFragmentManager().findFragmentById(R.id.frag_stitchdetail);
if (frag != null && frag.isInLayout()) {
//more code
frag.setRowID(stitchid);
}
setRowID is defined in the Fragment class:
public void setRowID(int row_id)
{
rowID = row_id;
}
and rowID is a private static int in the Fragment class.
Can someone please point me in the right direction?
Two options I can see.
One:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK) {
backPressed = true;
alert.show();
return true; // shows you consumed the event with your implementation
}
// blah, blah, other code
}
Add the following lines to your dialog yes and no OnClickListeners:
if (backPressed){
finish();// - to exit the Activity
}
Alternately, create two separate builders as follows:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// other code
builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Do you want to save your Notes?");
builder.setCancelable(false);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
saveNotes();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertSave = builder.create();
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
saveNotes();
finish();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
}
});
alertBack = builder.create();
ImageButton savebutton = (ImageButton)view.findViewById(R.id.savebutton);
savebutton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
alertSave.show();
}
});
// other code
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK) {
alertBack.show();
return true; // shows you consumed the event with your implementation
}
// blah, blah, other code
}
private void saveNotes() {
String Notes = notes.getText().toString();
Uri updateUri = ContentUris.withAppendedId(STITCHES_URI, rowID);
ContentValues values = new ContentValues();
values.put("stitchnotes", Notes);
getActivity().getContentResolver().update(updateUri,values,null,null);
}

Want to Refresh List View after change on item click

I am using ListView that get data from Database.
when i call update and delete i refresh the activity by call Intent.
it shows updated list but when i click on it it not shows changes in text view on which i am showing list details.
i am using Custom Adapter.Below is my code,
public class Mainmenu extends Activity{
ListView list;
DBHandler db= new DBHandler(this);
int ID;
String strname,strlastname,strdob,strcell,strcnic,straddress;
String pppath,cfpath,cbpath,fppath;
TextView tvname,tvlastname,tvdob,tvcnic,tvcell,tvaddress;
ImageView pp,cf,cb;
public static ArrayList<String> customers = new ArrayList<String>();
SearchResults sr1;
ArrayList<SearchResults> searchResults= new ArrayList<SearchResults>();
MyCustomBaseAdapter adaptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenulist);
list= (ListView) findViewById(R.id.listMM);
tvname=(TextView)findViewById(R.id.textView3);
tvlastname=(TextView)findViewById(R.id.textView4);
tvdob=(TextView)findViewById(R.id.textView5);
tvcnic=(TextView)findViewById(R.id.textView10);
tvcell=(TextView)findViewById(R.id.textView7);
tvaddress=(TextView)findViewById(R.id.textView8);
pp=(ImageView)findViewById(R.id.ImageView02);
cf=(ImageView)findViewById(R.id.imageView2);
cb=(ImageView)findViewById(R.id.ImageView03);
Context c =getApplicationContext();
if(db.getAllcustomers2().toString()==null){
db.getWritableDatabase();
db.init();
}else{
List<Customers_GS> gtEdu = db.getAllcustomers2();
customers.clear();
for (Customers_GS ed : gtEdu) {
sr1 = new SearchResults();
ID=ed.getCID();
sr1.setId(ID);
customers.add(ed.getCustomer_Name());
strname=ed.getCustomer_Name().toString();
sr1.setName(strname);
customers.add(ed.getCustomer_DOB());
strdob=ed.getCustomer_DOB().toString();
sr1.setDOB(strdob);
customers.add(ed.getCustomer_CNIC());
strcnic=ed.getCustomer_CNIC().toString();
sr1.setCNIC(strcnic);
customers.add(ed.getCustomer_Cell());
strcell=ed.getCustomer_Cell().toString();
sr1.setPhone(strcell);
customers.add(straddress);
straddress=ed.getCustomer_Address().toString();
sr1.setAddress(straddress);
customers.add(ed.getCustomer_PP());
pppath=ed.getCustomer_PP().toString();
customers.add(ed.getCustomer_CNICf());
cfpath=ed.getCustomer_CNICf().toString();
customers.add(ed.getCustomer_CNICb());
cbpath=ed.getCustomer_CNICb().toString();
customers.add(ed.getCustomer_Thumb());
sr1.setImageNumber(1);
searchResults.add(sr1);
}
}
adaptor= new MyCustomBaseAdapter(c, searchResults);
list.setAdapter(adaptor);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
int height= 146;
int width=146;
//parent.getItemAtPosition(position);
//
Log.d("PP", ""+pppath);
Log.d("cP", ""+cbpath);
Log.d("fP", ""+cfpath);
// Bitmap ppbitmap = BitmapFactory.decodeFile(pppath );
// Bitmap cbbitmap = BitmapFactory.decodeFile(cbpath );
// Bitmap cfbitmap = BitmapFactory.decodeFile(cfpath );
// ppbitmap=Bitmap.createScaledBitmap(ppbitmap, width,height, true);
// cbbitmap=Bitmap.createScaledBitmap(cbbitmap, width,height, true);
// cfbitmap=Bitmap.createScaledBitmap(cfbitmap, width,height, true);
//
// pp.setImageBitmap(ppbitmap);
// cb.setImageBitmap(cbbitmap);
// cf.setImageBitmap(cfbitmap);
String[] result =strname.split(" ");
strname= result[0];
strlastname=result[1];
tvname.setText(strname);
tvlastname.setText(strlastname);
tvcell.setText(strcell);
tvaddress.setText(straddress);
tvcnic.setText(strcnic);
tvdob.setText(strdob);
adaptor.notifyDataSetChanged();
}
});
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// // TODO Auto-generated method stub
//
//
db.getWritableDatabase();
// db.delete(ID);
// db.update(17);
// // TODO Auto-generated method stub
//
// Intent gonext= new Intent("com.example.ibex.MAINMENU");
// startActivity(gonext);
//
AlertDialog.Builder builder = new AlertDialog.Builder(Mainmenu.this);
builder.setMessage("Chose any one!");
builder.setCancelable(false);
builder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.update(ID);
Intent reload = new Intent(getApplicationContext(), Mainmenu.class);
startActivity(reload);
}
});
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.delete(ID);
Intent reload = new Intent(getApplicationContext(), Mainmenu.class);
startActivity(reload);
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
}
////### ## ##### ### ### ### ### #### ### ### ### ### ### ## ////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.optionmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.Addmenu){
Intent openstngs=new Intent("com.example.ibex.REGISTRATION");
startActivity(openstngs);
}else if(item.getItemId()==R.id.Edithmenu){
Bundle contan= new Bundle();
contan.putInt("key", ID );
Intent web =new Intent(Mainmenu.this, Edit.class);
web.putExtras(contan);
startActivity(web);
}else if(item.getItemId()==R.id.Dltmenu){
db.delete(ID);
Intent reload = new Intent(getApplicationContext(), Mainmenu.class);
startActivity(reload);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(Mainmenu.this);
builder.setMessage("Are u sure to want to Logout ?");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent reload = new Intent(getApplicationContext(), Login.class);
startActivity(reload);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
return super.onOptionsItemSelected(item);
};
}
I'm not clear about your question since you haven't provided the code of your adapter. I think You haven't called notifyDataSetChanged() method on your Adapter instance to get your changes reflected on ListView.

how to unselect all my checkbox

I'm trying without success to unselect all my checkbox picks
by pressing any button that in my java android program with this code
public void onListItemClick(ListView parent, View v, int position, long id)
{
parent.setItemChecked(position, parent.isItemChecked(position));
}
#Override
protected Dialog onCreateDialog(int id, Bundle args){
switch(id){
case 1:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"OK clicked!", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
})
.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(),items[which] + (isChecked ? " checked!":" unchecked!"),Toast.LENGTH_SHORT).show();
}
})
.create();
}
return(null);
}
how to select all and unselect all ?
Well, my best guess is to save a reference for all of them on a list, and go through all of them selecting or unselecting them all. Something like this.
Crete a reference to hold all your checkboxes
List<CheckBox> myCheckBoxes = new ArrayList<CheckBox>();
myCheckBoxes.add(cb1);
myCheckBoxes.add(cb2);
myCheckBoxes.add(cb3);
....
Create a method that will get the value you want to set on the check boxes and call it whenever you want.
:
private checkAll(boolean value) {
for(CheckBox cb : myCheckBoxes) {
cb.setChecked(value);
}
}
Create two buttons:
Button unselectAllButton = (Button) findViewById(R.id.unCheckButton);
Button selectAllButton = (Button) findViewById(R.id.checkButton);
unselectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(false);
}
});
selectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(true);
}
});

Categories