Dismiss Custom Alert Dialog on Back button pressed of hardware in android - android

I am having problem on back button of hardware. In my main Activity, I have one List view(say 1). When I click on item of this List view(1), one Alert Dialog appears, in this alert dialog, there is one List view(say 2). Data of this List view(2) are being repeated when I press back button of hardware. I have also put cancel image on this alert dialog to dismiss, when I press this cancel image, data are not being repeated. I tried different methods onResume(), onPause(), onDestroy(), onRestart() to clear the array for List view(2), but nothing works. Here is my code...
case LIST_DIALOG :
LayoutInflater inflater2 = LayoutInflater.from(this);
View dialogview1 = inflater2.inflate(R.layout.listdialog, null);
AlertDialog.Builder dialogbuilder2 = new AlertDialog.Builder(this);
dialogbuilder2.setView(dialogview1);
dialogDetails = dialogbuilder2.create();
case LIST_DIALOG:
AlertDialog alertDialog1 = (AlertDialog) dialog;
// Cancel Alert Dialog
ImageView ivCancel = (ImageView) alertDialog1.findViewById(R.id.imgCancel);
ivCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dismissDialog(LIST_DIALOG);
arr2.clear();
}
});
// Friend List
showFriendList();
break;
// List view data are inserted with this function call
private void showFriendList() {
// TODO Auto-generated method stub
Request.executeMyFriendsRequestAsync(friendSession, new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
// TODO Auto-generated method stub
// arr2 = new ArrayList<String>();
for(GraphUser user : users)
{
arr2.add(user.getName());
}
adapter2 = new ArrayAdapter<String>(getBaseContext(), R.layout.single_row, R.id.txt,arr2);
lvDialog.setAdapter(adapter2);
lvDialog.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
adapter2.notifyDataSetChanged();
itemCount = lvDialog.getCount();
Toast.makeText(getBaseContext(), "" + itemCount, 1000).show();
}
});
}
// I tried these methods, but nothing works...
#Override
public void onResume()
{
super.onResume();
ShowSavedFiles();
arr2.clear();
}
#Override
public void onPause()
{
super.onPause();
arr1.clear();
arr2.clear();
}
#Override
public void onBackPressed() {
//super.onBackPressed();
// finish your Activity
arr2.clear();
return;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
arr2.clear();
dismissDialog(LIST_DIALOG);
}
return false;
}

I'm not sure but might be adding the following code to your onKeyDown method might help out :
return super.onKeyDown(keyCode, event);

Related

how to get the previous checked position in list view

Actually I had a list view when I touch on the list view I will get popup window with check boxes when I check the check box and press OK then the dialog box closes and when I touch again the list view then the checked row position will change the background color and and stored into the data base. actually what was the issue is when I again select different item position and checked and press OK and again touch the list view instead of entering the checked position entering into data base the previously checked position also entering into data base along with current checked position. so I need to get previous position and clear position before the list view sees the checked positions. so that it only enters current position.
My activity
listView1.setOnTouchListener(new AdapterView.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
newListitems2.clear();
newListitems2.addAll(itemsList1);
dialog = new Dialog(PendingOrdersActitvity.this);
dialog.setContentView(R.layout.itembumping);
dialog.show();
//listView1.setTag(position);
list1 = (ListView) dialog.findViewById(R.id.list1);
ItemBumpingAdapter adapter2 = new ItemBumpingAdapter(PendingOrdersActitvity.this, newListitems2);
list1.setAdapter(adapter2);
Button okButton = (Button) dialog.findViewById(R.id.ok1);
okButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button cancelButton = (Button) dialog.findViewById(R.id.Cancel1);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}
return true;
}
});
Implimented code :
listView1.setOnTouchListener(new AdapterView.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
newListitems2.clear();
newListitems2.addAll(itemsList1);
dialog = new Dialog(PendingOrdersActitvity.this);
dialog.setContentView(R.layout.itembumping);
dialog.show();
list1=(ListView )dialog.findViewById(R.id.list1);
ItemBumpingAdapter adapter2 = new ItemBumpingAdapter(PendingOrdersActitvity.this,newListitems2);
list1.setAdapter(adapter2);
Button okButton = (Button)dialog.findViewById(R.id.ok1);
okButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Connection con1 = DbHandler.dbConnection();
try{
PreparedStatement stmt1 = con1
.prepareStatement("Select Line_No, ItemName,DeleteFlag from PendingOrders_Dtl where Inv_No=? ");
stmt1.setString(1,invNo);
ResultSet rsSetup1 = stmt1.executeQuery();
if (rsSetup1.next()) {
ItemsBean bean1 = new ItemsBean();
bean1.setLinenum(rsSetup1.getInt("Line_No"));
bean1.setProdnum(rsSetup1.getInt("ItemName"));
bean1.setDeleteFlag(rsSetup1.getInt("DeleteFlag"));
disablelist.add(bean1);
}
CustomAdapter adapter1 = new CustomAdapter(PendingOrdersActitvity.this, itemsList1);
for(int i=0;i<itemsList1.size();i++)
{
for(int j=0;j<disablelist.size();j++)
{
if(itemsList1.get(i).getProdnum()==disablelist.get(j).getProdnum())
{
itemsList1.get(i).setSelection(true);
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
try something like this
int previousPosition;
public int getPreviousPosition() {
return previousPosition;
}
public void setPreviousPosition(int previousPosition) {
this.previousPosition = previousPosition;
}
and in your listview on item selected listener
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int prePos= getPreviousPosition();
// do what ever you want to do with this prePos
View viewchild= parent.getChildAt(getPreviousPosition());
CheckBox prevCheckBox=(CheckBox)viewchild.findViewById(R.id.Checkbox_sort_list);
prevCheckBox.setChecked(false);
//at ending of list view write this
setPreviousPosition(position);
}
});
I think you have kept the checked positions in itemList1, so after you copy it to newListitems2, you need to clear the checked positions in newListitems2.
Try this:
listView1.setOnTouchListener(new AdapterView.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
newListitems2.clear();
newListitems2.addAll(itemsList1);
dialog = new Dialog(PendingOrdersActitvity.this);
dialog.setContentView(R.layout.itembumping);
dialog.show();
//listView1.setTag(position);
list1 = (ListView) dialog.findViewById(R.id.list1);
// Uncheck all items of newListitems2
for(int i=0; i<newListitems2.size(); i++){
ItemsBean tmpItem = newListitems2.get(i);
tmpItem.setChecked(false);
newListitems2.remove(i);
newListitems2.add(i, tmpItem);
}
ItemBumpingAdapter adapter2 = new ItemBumpingAdapter(PendingOrdersActitvity.this, newListitems2);
list1.setAdapter(adapter2);
Button okButton = (Button) dialog.findViewById(R.id.ok1);
okButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button cancelButton = (Button) dialog.findViewById(R.id.Cancel1);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}
return true;
}
});
For the other issue:
Method 1:
If the list in the popup dialog is the same as main list, then may be try: when dialog is dismissed, get the list from popup dialog and copy it to main list.
Add method in Adapter class to get the list from adapter2:
public ArrayList<ItemsBean> getItemList(){
return newListitems;
}
When okbutton clicked, over-write the main list and dismiss the dialog:
itemsList1 = adapter2.getItemList();
adapter1 = new ItemBumpingAdapter(PendingOrdersActitvity.this, itemList1);
adapter1.notifyDataSetChanged();
dialog.dismiss();
Method 2:
Add method to adapter1 to check items:
public void checkItemsAccordingDatabase(){
for(int i=0; i<newListItems; i++){
ItemsBean tmpItem = newListItems.get(i);
// query tmpItem in database.
// if tmpItem exits, newListItems.get(i).setChecked(true).
}
notifyDataSetChanged();
}
When okbutton clicked, update the main list and dismiss the dialog:
adapter1.checkItemsAccordingDatabase();
dialog.dismiss();
Try this:
// Move this after setSelection.
// CustomAdapter adapter1 = new CustomAdapter(PendingOrdersActitvity.this, itemsList1);
for(int i=0;i<itemsList1.size();i++){
for(int j=0;j<disablelist.size();j++){
if(itemsList1.get(i).getProdnum()==disablelist.get(j).getProdnum()){
itemsList1.get(i).setSelection(true);
break;
}
}
}
CustomAdapter adapter1 = new CustomAdapter(PendingOrdersActitvity.this, itemsList1);
listView1.setAdapter(adapter1);
And modify getView() of CustomAdapter similar to your ItemBumpingAdapter:
if(newListItems.isSelected()){
convertView.setBackgroundColor(...);
else{
convertView.setBackgroundColor(...);
}
retrun convertView;

IllegalStateException: Fragment not attached to Activity when finish AsyncTask & Fragment

I am using ProgressDialog in AsyncTask. And If user Press Back Button, then AsyncTask will be cancelled, current fragment will replace by any other Fragment.
There is no issue if user is still on Application. Bu if he goes back and back speedly and at last stop application, It gives error IllegalStateException: Fragment not attached to Activity.
How to solve this ?
My Code:
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", "Loading...", true,
true, new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
CancelDialog();
}
});
}
public void CancelDialog() {
new FetchData().cancel(true);
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
((FrameLayout) flMain).removeAllViews();
fm.beginTransaction().add(R.id.frame, new Home()).commit();
}
Home.java:
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
getView().clearFocus();
getActivity().finish();
return true;
}
return false;
}
});
}
After so many tried, lastly I have found Simple Answer: isAdded()
It will Return true if the Fragment is currently added to its Activity.
I used below code and it solved my problem.
#Override
protected void onPostExecute(Void result){
if(isAdded()){
// Code to display Data...
}
}
You should be careful when to call e.g getActivity() - your fragment might not (yet/already) be attached to an activity when you call such methods. Check out this.
Alternatively you can save the Activity instance when onAttach is called, but then you'll have to be careful what you do with that Activity instance, so that you do not make conflicting updates with another Fragment that is actually still attached.
isAdded and isDetached can be useful to check the state and avoid calling invalid methods.

PopUpWindow Back Key event

I saw many posts on this subject but couldnt find the right answer for me.
I have an activity that dims when i pop the popup window.
the back button working but only the second time i press it, the first press dismiss the popup but its not un-dim the activity because i cant catch the event from the popupwindows, the second press is catched by the activity and only then i can un-dim it.
here are my tries to accomplish this:
m_PopupWindow.setBackgroundDrawable(new BitmapDrawable());
m_PopupWindow.setOutsideTouchable(true);
View popUpWindowLaout = m_PopupWindow.getContentView();
popUpWindowLaout.setFocusableInTouchMode(true);
//first press doesnt get caught here
popUpWindowLaout.setOnKeyListener(new View.OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
return true;
}
}
});
//this func will catch the second press and will work, but i want the first press will do it.
#Override
public void onBackPressed() {
if (m_PopupWindow != null)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
}
else
{
super.onBackPressed();
}
}
change
public void onBackPressed() {
if (m_PopupWindow != null)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
}
else
{
super.onBackPressed();
}
}
to
public void onBackPressed() {
super.onBackPressed();
if (m_PopupWindow != null)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
}
else
{
// rest of the code
// you can use finish,dismiss or call startActivity
// finish();
}
}
popupWindow.setOnShowListener(HandlePopupShowLister);
popupWindow.setOnDismissListener(HandlePopUpDismissListerner);
public static OnDismissListener HandlePopUpDismissListerner = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
Log.i("HandlePopUpDismissListerner", "HandlePopUpDismissListerner");
CommonVariable.IsPopupOpen = false;
}
};
public static OnShowListener HandlePopupShowLister = new OnShowListener() {
// onShowListener interface.
#Override
public void onShow(DialogInterface dialog) {
Log.i("HandlePopupShowLister", "HandlePopupShowLister");
// TODO Auto-generated method stub
CommonVariable.IsPopupOpen = true;
}
};

Alert Dialog dismissing on ScreenLock

My Alert Dialog is dismissing when screen is locked and Unlocked.In my case,
1)Starting connection in asynctask (which is inner class),here progress dialog starts saying "please wait...".
2)After completion of connection ProgressDilog is dismissed and Alert Message is shown.
So,In this process when i lock the screen when Connection is started, Alert Message is not shown and the same Activity in previous state is shown.
alertBuilder = new AlertDialog.Builder(Registration.this);
alertBuilder.setMessage(Constants.TEXT_REGISTERED_SUCCESSFULLY);
alertBuilder.setCancelable(false);
alertBuilder.setPositiveButton(Constants.TEXT_OK, new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Util.saveData(Registration.this);
Intent thanksYouIntent = new Intent(Registration.this,ThankYouActivity.class);
Registration.this.finish();
} });
alertBuilder.create().show();
This is my Code for raising the dialog.I heard to bind the dialog to activity so i tried like alertBuilder.create().setOwnerActivity(RegistrationActivity.this).This is also not showing any results.
One thing I have no clarity is what happens to inner asyncTask which is running Connection when the parent activity is paused.Any body plz help me out.
Thanks in advance,
Sha.
Correct me if am wrong.Form my observation when an activity is in paused state,the corresponding AsyncTask is stopped.
So,In my case when screen is locked connection which is in doInBackground of asynctask already starts execution.But due to the screen lock reasons asyncTask is stopped and onPostExecute is not Completing successfully.My alertDialog which is in onpostexecute is not displaying.So,I'm saving the response state of the connection and displaying it when oncreate is called on screen Unlock using a boolean check.
The below is the code.This is huge but couldn't cut more than that to explain my case.
private static boolean alertDialogDismissedUnExpectedly;
private static String _alertMessage; //alert Message is for saving the previous alert message displaying when screen is locked
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//coding part
_registerImageView.setOnClickListener(new OnClickListener() {//here the asynctask starts running on click
private String _response;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
_alertMessage = "";
//post data for response
String postcontent="Sucess";
if(Constants.LOG)Log.d("Content to post is :", ""+postcontent);
ResgiserAsyncTask asyncTask = new ResgiserAsyncTask(postcontent);
asyncTask.execute(null);
}
if(alertDialogDismissedUnExpectedly && savedInstanceState != null){ // check for Alert Message dismissed unexpectedly
if(_alertMessage == null ? true : _alertMessage.equalsIgnoreCase("")){ //intialise the last state of alert message if no alert message is set
_alertMessage = _Engine.get_returnMessage();//this is my engine where parsing is done,So i'll get the previous response of connection
}
if(_alertMessage != null){
if(_alertMessage.equalsIgnoreCase(Constants.TEXT_REGISTERED_SUCCESSFULLY) || _alertMessage.equalsIgnoreCase(Constants.TEXT_SUCCESS)){//my success case
raiseSuccessDialog();//this is internal method
}else{//failure case
raiseDialog(_alertMessage);//this is internal method
}
}
}else{
alertDialogDismissedUnExpectedly = false;
_alertMessage = "";
}
}
private class ResgiserAsyncTask extends AsyncTask{
private String _postContent;
private Document _document;
public ResgiserAsyncTask(String postContent) {
// TODO Auto-generated constructor stub
alertDialogDismissedUnExpectedly = true;//set the coolean to true and make it false Clicklistener of alertDialog
_postContent= postContent;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
_document = Util.postPage(Constants.URL_REGISTRATION, _postContent, true);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(_document != null){
String _response = _Engine.parseRegistration(_document);
if(!Constants.TEXT_SUCCESS.equalsIgnoreCase(_response)){
raiseDialog(_response);
}else{
raiseSuccessDialog();
}
}
}
}
private void raiseSuccessDialog(){
_alertMessage = Constants.TEXT_REGISTERED_SUCCESSFULLY;
alertBuilder = new AlertDialog.Builder(Registration.this);
alertBuilder.setMessage(Constants.TEXT_REGISTERED_SUCCESSFULLY);
alertBuilder.setCancelable(false);
alertBuilder.setPositiveButton(Constants.TEXT_OK, new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
alertDialogDismissedUnExpectedly = false;
Intent thanksYouIntent = new Intent(Registration.this,ThankYouActivity.class);
startActivity(thanksYouIntent);
}
});
alertBuilder.create().show();
}
private void raiseDialog(String message) {
// TODO Auto-generated method stub
_alertMessage = message; // intialise the message to the raised dialog so that when screen is locked the alert can be displayed once again
AlertDialog.Builder alertBuilder = new Builder(Registration.this);
alertBuilder.setMessage(message);
alertBuilder.setCancelable(false);
alertBuilder.setPositiveButton(Constants.TEXT_OK, new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
alertDialogDismissedUnExpectedly = false;
}
});
alertBuilder.create().show();
}
Hope it helps for those who faced the same problem.Any better ideas invited.
Override onCreateDialog() for showing dialogs. It can helps.
#sha
there are some events raised during screen off and on you need to control that too.... the link http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/ shoes some examples regarding this

Click issue in android

In my application i am displaying rows dynamically.
I am using the below code so as to focus the clicked row even if the user press back key.
But the issue is like if the row is not focussed we need two clicka to navigate.First to make it focussable and then next click to navigate.I need all at once any suggestions.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int a=0;a>16;a++)
{
tr[a].setBackgroundColor(Color.BLACK);
}
flag=v.getId();
if(v.getId()==1)
{
Intent i = new Intent(TableImageLayout.this, TableImageLayout3.class);
startActivity(i);
}
if(v.getId()==3)
{
Intent i = new Intent(TableImageLayout.this, TableImageLayout3.class);
startActivity(i);
}
if(v.getId()==5)
{
Intent i = new Intent(TableImageLayout.this, TableImageLayout3.class);
startActivity(i);
}
if(v.getId()==7)
{
Intent i = new Intent(TableImageLayout.this, TableImageLayout3.class);
startActivity(i);
}
if(v.getId()==100)
{
Intent i = new Intent(TableImageLayout.this, TableImageLayout3.class);
startActivity(i);
}
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
for(int a=0;a>16;a++)
{
tr[a].setBackgroundColor(Color.BLACK);
}
if(hasFocus)
{
((TableRow)v).setBackgroundColor(Color.rgb(255, 180, 40));
}
else
{((TableRow)v).setBackgroundColor(Color.BLACK);}
}
protected void onResume() {
super.onResume();
for(int a=0;a>16;a++)
{
tr[a].setBackgroundColor(Color.BLACK);
}
tr[flag].requestFocus();
tr[flag].setFocusableInTouchMode(true);
tr[flag].setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus)
{
((TableRow)v).setBackgroundColor(Color.rgb(255, 180, 40));
}
else
{((TableRow)v).setBackgroundColor(Color.BLACK);}
}
});
}
#Override
public void onPause() {
super.onPause();
}
Please let me know your valuable suggestions.
Thanks in advance.
If your only need for focus listener is to change background colors, you would do better setting their background to a drawable that has different backgrounds for focused and normal states, then you don't need to control it in code at all. As for requiring two clicks to navigate, I don't see anything in your code about it. It seems to start an activity as soon as a view is clicked once.

Categories

Resources