Rectangle 27 78

No, if some activity comes into foreground, that doesn't necessarily mean that the other activity is completely invisible. Consider the following case:

Here we see both activities at the same time. The first activity with the fields is obscured by another activity, and the user can no longer interact with it. However, it is still visible with all the resulting consequences.

That leaves a question which activity is considered fully opaque and covering the whole screen and which isn't. This decision is based on the window containing the activity. If the window has a flag windowIsFloating or windowIsTranslucent, then it is considered that the activity doesn't make the underlying stuff invisible, otherwise it does and will cause onStop() to be called. The relevant code can be found in com.android.server.am.ActivityRecord:

fullscreen = ent != null && !ent.array.getBoolean(
        com.android.internal.R.styleable.Window_windowIsFloating, false)
        && !ent.array.getBoolean(
        com.android.internal.R.styleable.Window_windowIsTranslucent, false);

+1 for a great explanation, focusing on partial vs. total (in)visibility. It would be interesting to know the threshold percentage of the screen that makes Android decide between onPause() and onStop(). Is it 100%? If only one pixel from the previous activity is visible, is it still onPause()?

@ateiob It is not said anywhere, but I think so. However, it is usually obvious because most activities which don't fill entire screen simply use one of the system provided styles for dialogs.

Strange, but in my application onPause() isn't called at all when a dialog is displayed. onPause() is only called when I press the home button. How is this possible?

@GMsoF An activity. That's the main point: not every dialog is actually a dialog. You can make an activity look like a dialog, so it is actually smaller than the entire screen.

android - Difference between onPause and onStop() - Stack Overflow

android android-activity android-lifecycle
Rectangle 27 25

If you can still see any part of it (Activity coming to foreground either doesn't occupy the whole screen, or it is somewhat transparent), onPause() will be called. If you cannot see any part of it, onStop() will be called.

A dialog**, for example, may not cover the entire previous Activity, and this would be a time for onPause() to be called.

**I am not referring to an Android Dialog here, rather a conceptual idea of something that pops up and only obscures part of the user screen. This note was added to clarify based on a comment from @GMsoF below

@GMsoF It sounds like when I said dialog, you thought I meant Dialog, as in the Android class. What I was getting at, though, is something that partly obscures the first Activity to illustrate the idea that all new Activity's do not need to completely cover up the previous.

android - Difference between onPause and onStop() - Stack Overflow

android android-activity android-lifecycle
Rectangle 27 9

Being in the foreground means that the activity has input focus. For instance, an activity can be visible but partially obscured by a dialog that has focus. In that case, onPause() will be called, but not onStop(). When the dialog goes away, the activity's onResume() method will be called (but not onStart()).

The dialog thing could be misleading. Let's a warning dialog is popped up from the main UI thread of this activity, onPause() will not be called in this case. Only if this dialog is popped up from other Activity or other App.

android - Difference between onPause and onStop() - Stack Overflow

android android-activity android-lifecycle
Rectangle 27 122

You can use forwarding to remove the previous activity from the activity stack while launching the next one. There's an example of this in the APIDemos, but basically all you're doing is calling finish() immediately after calling startActivity().

Hi Daniel, I read through the example, but that will only clear the history stack by 1 activity, won't it? If my stack looks like A, B, and I'm launching C, I want C to be the new root and completely clear A and B. In the sdk example, calling finish() from B would leave me with a stack of A, C, wouldn't it? Thanks.

You could clear A as you launch B, and clear B as you launch C; however, I suppose then you wouldn't be able to back out from B to A if that's what you desire. I'll have to think on this more if that's a problem.

Mark, to achieve what you want, you have to use the flag: FLAG_ACTIVITY_CLEAR_TOP. I hope it helps.

FLAG_ACTIVITY_CLEAR_TOP won't work because C isn't already in the back stack.

@DanielLew There are so many examples in the APIDemos. You'd have the name of the example suggested ?

android - Removing an activity from the history stack - Stack Overflow

android android-activity activity-lifecycle
Rectangle 27 40

Example of Calling

import Foundation
import Security

// Constant Identifiers
let userAccount = "AuthenticatedUser"
let accessGroup = "SecuritySerivice"


/** 
 *  User defined keys for new entry
 *  Note: add new keys for new secure item and use them in load and save methods
 */

let passwordKey = "KeyForPassword"

// Arguments for the keychain queries
let kSecClassValue = NSString(format: kSecClass)
let kSecAttrAccountValue = NSString(format: kSecAttrAccount)
let kSecValueDataValue = NSString(format: kSecValueData)
let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword)
let kSecAttrServiceValue = NSString(format: kSecAttrService)
let kSecMatchLimitValue = NSString(format: kSecMatchLimit)
let kSecReturnDataValue = NSString(format: kSecReturnData)
let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne)

public class KeychainService: NSObject {

    /**
     * Exposed methods to perform save and load queries.
     */

    public class func savePassword(token: NSString) {
        self.save(passwordKey, data: token)
    }

    public class func loadPassword() -> NSString? {
        return self.load(passwordKey)
    }

    /**
     * Internal methods for querying the keychain.
     */

    private class func save(service: NSString, data: NSString) {
        let dataFromString: NSData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

        // Instantiate a new default keychain query
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])

        // Delete any existing items
        SecItemDelete(keychainQuery as CFDictionaryRef)

        // Add the new keychain item
        SecItemAdd(keychainQuery as CFDictionaryRef, nil)
    }

    private class func load(service: NSString) -> NSString? {
        // Instantiate a new default keychain query
        // Tell the query to return a result
        // Limit our results to one item
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

        var dataTypeRef :AnyObject?

        // Search for the keychain items
        let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
        var contentsOfKeychain: NSString? = nil

        if status == errSecSuccess {
            if let retrievedData = dataTypeRef as? NSData {
                contentsOfKeychain = NSString(data: retrievedData, encoding: NSUTF8StringEncoding)
            }
        } else {
            print("Nothing was retrieved from the keychain. Status code \(status)")
        }

        return contentsOfKeychain
    }
}
KeychainService.savePassword("Pa55worD")
let password = KeychainService.loadPassword() // password = "Pa55worD"
import Cocoa
import Security

// see https://stackoverflow.com/a/37539998/1694526
// Arguments for the keychain queries
let kSecClassValue = NSString(format: kSecClass)
let kSecAttrAccountValue = NSString(format: kSecAttrAccount)
let kSecValueDataValue = NSString(format: kSecValueData)
let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword)
let kSecAttrServiceValue = NSString(format: kSecAttrService)
let kSecMatchLimitValue = NSString(format: kSecMatchLimit)
let kSecReturnDataValue = NSString(format: kSecReturnData)
let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne)

public class KeychainService: NSObject {

    class func updatePassword(service: String, account:String, data: String) {
        if let dataFromString: Data = data.data(using: String.Encoding.utf8, allowLossyConversion: false) {

            // Instantiate a new default keychain query
            let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

            let status = SecItemUpdate(keychainQuery as CFDictionary, [kSecValueDataValue:dataFromString] as CFDictionary)

            if (status != errSecSuccess) {
                if let err = SecCopyErrorMessageString(status, nil) {
                    print("Read failed: \(err)")
                }
            }
        }
    }


    class func removePassword(service: String, account:String) {

        // Instantiate a new default keychain query
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

        // Delete any existing items
        let status = SecItemDelete(keychainQuery as CFDictionary)
        if (status != errSecSuccess) {
            if let err = SecCopyErrorMessageString(status, nil) {
                print("Remove failed: \(err)")
            }
        }

    }


    class func savePassword(service: String, account:String, data: String) {
        if let dataFromString = data.data(using: String.Encoding.utf8, allowLossyConversion: false) {

            // Instantiate a new default keychain query
            let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])

            // Add the new keychain item
            let status = SecItemAdd(keychainQuery as CFDictionary, nil)

            if (status != errSecSuccess) {    // Always check the status
                if let err = SecCopyErrorMessageString(status, nil) {
                    print("Write failed: \(err)")
                }
            }
        }
    }

    class func loadPassword(service: String, account:String) -> String? {
        // Instantiate a new default keychain query
        // Tell the query to return a result
        // Limit our results to one item
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

        var dataTypeRef :AnyObject?

        // Search for the keychain items
        let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
        var contentsOfKeychain: String?

        if status == errSecSuccess {
            if let retrievedData = dataTypeRef as? Data {
                contentsOfKeychain = String(data: retrievedData, encoding: String.Encoding.utf8)
            }
        } else {
            print("Nothing was retrieved from the keychain. Status code \(status)")
        }

        return contentsOfKeychain
    }

}

You need to imagine the following wired up to a text input field and a label, then having four buttons wired up, one for each of the methods.

class ViewController: NSViewController {
    @IBOutlet weak var enterPassword: NSTextField!
    @IBOutlet weak var retrievedPassword: NSTextField!

    let service = "myService"
    let account = "myAccount"

    // will only work after
    @IBAction func updatePassword(_ sender: Any) {
        KeychainService.updatePassword(service: service, account: account, data: enterPassword.stringValue)
    }

    @IBAction func removePassword(_ sender: Any) {
        KeychainService.removePassword(service: service, account: account)
    }

    @IBAction func passwordSet(_ sender: Any) {
        let password = enterPassword.stringValue
        KeychainService.savePassword(service: service, account: account, data: password)
    }

    @IBAction func passwordGet(_ sender: Any) {
        if let str = KeychainService.loadPassword(service: service, account: account) {
            retrievedPassword.stringValue = str
        }
        else {retrievedPassword.stringValue = "Password does not exist" }
    }
}

Thanks a lot for this! I just have one question here. For saving password, you are first deleting and then adding. Would it have not been better to first check if the password exists and then either update or add it to keychain? What are the pros/cons of this approach over the other?

I find this much easier to understand than the answers to the duplicate question. I've edited to include updating, which the save code now implements automatically if it is unable to overwrite an existing password (rather than attempting a delete ahead of time). There is also an added method for removing a password. You will find in Swift 3 that you'll need to do some casting to NSString where this doesn't happen automatically anymore but apart from that all should work.

did someone fix the remove & update methods? i have the same problem (error code -50)

I was running into the -50 OSStatus errors on the delete function and corrected it by removing the kSecReturnDataValue and kSecMatchLimitValue items from the keychain query before the SecItemDelete call. The -50 indicates a problem with the parameters that were passed into the function. Removing those two fixed it for me. I'm assuming the same problem exists in the update function but I haven't tried working with that one yet.

ios - Save and Load from KeyChain | Swift - Stack Overflow

ios swift security keychain
Rectangle 27 37

Example of Calling

import Foundation
import Security

// Constant Identifiers
let userAccount = "AuthenticatedUser"
let accessGroup = "SecuritySerivice"


/** 
 *  User defined keys for new entry
 *  Note: add new keys for new secure item and use them in load and save methods
 */

let passwordKey = "KeyForPassword"

// Arguments for the keychain queries
let kSecClassValue = NSString(format: kSecClass)
let kSecAttrAccountValue = NSString(format: kSecAttrAccount)
let kSecValueDataValue = NSString(format: kSecValueData)
let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword)
let kSecAttrServiceValue = NSString(format: kSecAttrService)
let kSecMatchLimitValue = NSString(format: kSecMatchLimit)
let kSecReturnDataValue = NSString(format: kSecReturnData)
let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne)

public class KeychainService: NSObject {

    /**
     * Exposed methods to perform save and load queries.
     */

    public class func savePassword(token: NSString) {
        self.save(passwordKey, data: token)
    }

    public class func loadPassword() -> NSString? {
        return self.load(passwordKey)
    }

    /**
     * Internal methods for querying the keychain.
     */

    private class func save(service: NSString, data: NSString) {
        let dataFromString: NSData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

        // Instantiate a new default keychain query
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])

        // Delete any existing items
        SecItemDelete(keychainQuery as CFDictionaryRef)

        // Add the new keychain item
        SecItemAdd(keychainQuery as CFDictionaryRef, nil)
    }

    private class func load(service: NSString) -> NSString? {
        // Instantiate a new default keychain query
        // Tell the query to return a result
        // Limit our results to one item
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

        var dataTypeRef :AnyObject?

        // Search for the keychain items
        let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
        var contentsOfKeychain: NSString? = nil

        if status == errSecSuccess {
            if let retrievedData = dataTypeRef as? NSData {
                contentsOfKeychain = NSString(data: retrievedData, encoding: NSUTF8StringEncoding)
            }
        } else {
            print("Nothing was retrieved from the keychain. Status code \(status)")
        }

        return contentsOfKeychain
    }
}
KeychainService.savePassword("Pa55worD")
let password = KeychainService.loadPassword() // password = "Pa55worD"
import Cocoa
import Security

// see https://stackoverflow.com/a/37539998/1694526
// Arguments for the keychain queries
let kSecClassValue = NSString(format: kSecClass)
let kSecAttrAccountValue = NSString(format: kSecAttrAccount)
let kSecValueDataValue = NSString(format: kSecValueData)
let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword)
let kSecAttrServiceValue = NSString(format: kSecAttrService)
let kSecMatchLimitValue = NSString(format: kSecMatchLimit)
let kSecReturnDataValue = NSString(format: kSecReturnData)
let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne)

public class KeychainService: NSObject {

    class func updatePassword(service: String, account:String, data: String) {
        if let dataFromString: Data = data.data(using: String.Encoding.utf8, allowLossyConversion: false) {

            // Instantiate a new default keychain query
            let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

            let status = SecItemUpdate(keychainQuery as CFDictionary, [kSecValueDataValue:dataFromString] as CFDictionary)

            if (status != errSecSuccess) {
                if let err = SecCopyErrorMessageString(status, nil) {
                    print("Read failed: \(err)")
                }
            }
        }
    }


    class func removePassword(service: String, account:String) {

        // Instantiate a new default keychain query
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

        // Delete any existing items
        let status = SecItemDelete(keychainQuery as CFDictionary)
        if (status != errSecSuccess) {
            if let err = SecCopyErrorMessageString(status, nil) {
                print("Remove failed: \(err)")
            }
        }

    }


    class func savePassword(service: String, account:String, data: String) {
        if let dataFromString = data.data(using: String.Encoding.utf8, allowLossyConversion: false) {

            // Instantiate a new default keychain query
            let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])

            // Add the new keychain item
            let status = SecItemAdd(keychainQuery as CFDictionary, nil)

            if (status != errSecSuccess) {    // Always check the status
                if let err = SecCopyErrorMessageString(status, nil) {
                    print("Write failed: \(err)")
                }
            }
        }
    }

    class func loadPassword(service: String, account:String) -> String? {
        // Instantiate a new default keychain query
        // Tell the query to return a result
        // Limit our results to one item
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, account, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

        var dataTypeRef :AnyObject?

        // Search for the keychain items
        let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
        var contentsOfKeychain: String?

        if status == errSecSuccess {
            if let retrievedData = dataTypeRef as? Data {
                contentsOfKeychain = String(data: retrievedData, encoding: String.Encoding.utf8)
            }
        } else {
            print("Nothing was retrieved from the keychain. Status code \(status)")
        }

        return contentsOfKeychain
    }

}

You need to imagine the following wired up to a text input field and a label, then having four buttons wired up, one for each of the methods.

class ViewController: NSViewController {
    @IBOutlet weak var enterPassword: NSTextField!
    @IBOutlet weak var retrievedPassword: NSTextField!

    let service = "myService"
    let account = "myAccount"

    // will only work after
    @IBAction func updatePassword(_ sender: Any) {
        KeychainService.updatePassword(service: service, account: account, data: enterPassword.stringValue)
    }

    @IBAction func removePassword(_ sender: Any) {
        KeychainService.removePassword(service: service, account: account)
    }

    @IBAction func passwordSet(_ sender: Any) {
        let password = enterPassword.stringValue
        KeychainService.savePassword(service: service, account: account, data: password)
    }

    @IBAction func passwordGet(_ sender: Any) {
        if let str = KeychainService.loadPassword(service: service, account: account) {
            retrievedPassword.stringValue = str
        }
        else {retrievedPassword.stringValue = "Password does not exist" }
    }
}

Thanks a lot for this! I just have one question here. For saving password, you are first deleting and then adding. Would it have not been better to first check if the password exists and then either update or add it to keychain? What are the pros/cons of this approach over the other?

I find this much easier to understand than the answers to the duplicate question. I've edited to include updating, which the save code now implements automatically if it is unable to overwrite an existing password (rather than attempting a delete ahead of time). There is also an added method for removing a password. You will find in Swift 3 that you'll need to do some casting to NSString where this doesn't happen automatically anymore but apart from that all should work.

did someone fix the remove & update methods? i have the same problem (error code -50)

I was running into the -50 OSStatus errors on the delete function and corrected it by removing the kSecReturnDataValue and kSecMatchLimitValue items from the keychain query before the SecItemDelete call. The -50 indicates a problem with the parameters that were passed into the function. Removing those two fixed it for me. I'm assuming the same problem exists in the update function but I haven't tried working with that one yet.

ios - Save and Load from KeyChain | Swift - Stack Overflow

ios swift security keychain
Rectangle 27 238

2. Calling the Contact Picker

I'm not 100% sure what your sample code is supposed to do, but the following snippet should help you 'call the contacts list function, pick a contact, then return to [your] app with the contact's name'.

Add a permission to read contacts data to your application manifest.

<uses-permission android:name="android.permission.READ_CONTACTS"/>

Within your Activity, create an Intent that asks the system to find an Activity that can perform a PICK action from the items in the Contacts URI.

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);

Call startActivityForResult, passing in this Intent (and a request code integer, PICK_CONTACT in this example). This will cause Android to launch an Activity that's registered to support ACTION_PICK on the People.CONTENT_URI, then return to this Activity when the selection is made (or canceled).

startActivityForResult(intent, PICK_CONTACT);

Also in your Activity, override the onActivityResult method to listen for the return from the 'select a contact' Activity you launched in step 2. You should check that the returned request code matches the value you're expecting, and that the result code is RESULT_OK.

You can get the URI of the selected contact by calling getData() on the data Intent parameter. To get the name of the selected contact you need to use that URI to create a new query and extract the name from the returned cursor.

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
  super.onActivityResult(reqCode, resultCode, data);

  switch (reqCode) {
    case (PICK_CONTACT) :
      if (resultCode == Activity.RESULT_OK) {
        Uri contactData = data.getData();
        Cursor c =  getContentResolver().query(contactData, null, null, null, null);
        if (c.moveToFirst()) {
          String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
          // TODO Whatever you want to do with the selected contact name.
        }
      }
      break;
  }
}

it appears that a lot of this code has been deprecated with the recent android APIs. Does someone have an updated version?

Q: If I want to kick off a subactivity upon picking a contact (so that we have a way to back up to the contact list again), would Intent.ACTION_PICK still work? I'm starting to think I have to roll my own cursor and use setListAdapter, like in the main question. Hmm ...

Nothing is wrong here... you don't need the READ contact permission as the user is in control here. The app itself doesn't internally read the contacts, but rather pops a contact list. Only when the user selects a contact (manual action) is the app capable of retrieving a limited set of that of data associated with that contact info.

I was able to let user pick a contact without READ permission on my 4.0+ Android phone but not on 1.6. Anybody know at what version did this functionality come about?

How to call Android contacts list? - Stack Overflow

android contacts
Rectangle 27 497

setCompoundDrawablesWithIntrinsicBounds

thankyou very much .. this works for me.. may i know whats the difference between these two ?

ok, why? can you explain?

android - Calling setCompoundDrawables() doesn't display the Compound ...

android android-layout android-drawable
Rectangle 27 422

...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...

yes this works. but if you want to start multiple instances of the same Activity this does not work. Since the FLAG_ACTIVITY_NEW_TASK will resume the same existing Activity

android - Calling startActivity() from outside of an Activity? - Stack...

android alarmmanager android-pendingintent runtimeexception
Rectangle 27 386

  • cache the Context object via constructor in your adapter, or

Or as a last resort,

myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Edit - i would avoid setting flags as it will interfere with normal flow of event and history stack.

What about the autoLink feature of the TextView where I can not control Intent (and thus flags) created by the system?

I was getting this exception when I was doing something like this context.startActivity(intent); I just changed contextfrom ApplicationContext to Activity type. This fixed the problem.

@AlexSemeniuk ever find a solution?

ClickableSpan

android - Calling startActivity() from outside of an Activity context ...

android android-activity android-context
Rectangle 27 1

The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.

android - Difference between onPause and onStop() - Stack Overflow

android android-activity android-lifecycle
Rectangle 27 153

OK that was easy, thanks (I'm brand new to fragments). Now the hard part is I can't seem to get a reference to the fragment in the first place. It's not defined in an XML layout, so I can't use findFragmentById(). And it's not clear to me from the code I'm following (ref above) how/where the fragment is even created. If it were I could just add a tag and use findFragmentByTag(). The AccountListActivity part of the example does have a call to beginTransaction().add(), but per my trace it's never called. This is where I am scratching my head. I appreciate any suggestions.

Sorry, I left out the reference. The code pattern I am following is FragmentTabsPager. Thanks.

The situation will be different when neither u are having the ID nor the TAG associated with the fragment .

how can I get the fragment id?

By doing this i ended up in a null object reference!

android - Calling a Fragment method from a parent Activity - Stack Ove...

android android-fragments
Rectangle 27 1

did you try not calling finish, and putting "android:noHistory="true" in the manifest? this will prevent the activity from going to the stack.

android - How to check if activity is in foreground or in visible back...

android android-activity dialog activity-finish
Rectangle 27 63

Where R.id.example_fragment is most likely the FrameLayout id inside your xml layout. OR

Where FragTagName is the name u specified when u did:

TabHost mTabHost.newTabSpec(FragTagName)

If you are using import android.support.v4.app.Fragment; Then use either:

ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.example_fragment); 
fragment.specific_function_name();
ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentByTag(FragTagName); 
fragment.specific_function_name();

I have a CoordinatorLayout with id R.id.example_fragment, its returning null. I'm using import android.support.v4.app.Fragment; what to do?

I suggest you post this as a new question and include your sample code. It's hard to tell the source of the problem without seeing the actual code.

android - Calling a Fragment method from a parent Activity - Stack Ove...

android android-fragments
Rectangle 27 61

public interface ServiceCallbacks {
    void doSomething();
}

Write your Service class. Your Activity will bind to this service, so follow the sample shown here. In addition, we will add a method to set the ServiceCallbacks.

public class MyService extends Service {
    // Binder given to clients
    private final IBinder binder = new LocalBinder();
    // Registered callbacks
    private ServiceCallbacks serviceCallbacks;


    // Class used for the client Binder.
    public class LocalBinder extends Binder {
        MyService getService() {
            // Return this instance of MyService so clients can call public methods
            return MyService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public void setCallbacks(ServiceCallbacks callbacks) {
        serviceCallbacks = callbacks;
    }
}

Write your Activity class following the same guide, but also make it implement your ServiceCallbacks interface. When you bind/unbind from the Service, you will register/unregister it by calling setCallbacks on the Service.

public class MyActivity extends Activity implements ServiceCallbacks {
    private MyService myService;
    private boolean bound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(...);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // bind to Service
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from service
        if (bound) {
            myService.setCallbacks(null); // unregister
            unbindService(serviceConnection);
            bound = false;
        }
    }

    /** Callbacks for service binding, passed to bindService() */
    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // cast the IBinder and get MyService instance
            LocalBinder binder = (LocalBinder) service;
            myService = binder.getService();
            bound = true;
            myService.setCallbacks(MyActivity.this); // register
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            bound = false;
        }
    };

    /* Defined by ServiceCallbacks interface */
    @Override
    public void doSomething() {
        ...
    }
}

Now when your service wants to communicate back to the activity, just call one of the interface methods from earlier. Inside your service:

if (serviceCallbacks != null) { 
    serviceCallbacks.doSomething();
}

@Vlad It appears I was using the same identifier for both the class member and a method parameter. I've made the necessary corrections.

It gives an error: '04-17 03:03:46.715: E/AndroidRuntime(25591): java.lang.ClassCastException: android.os.BinderProxy cannot be cast to com.example.create.main.RePublishService$LocalBinder ' ; I need my Service to run on a separate process.

android - Calling activity class method from Service class - Stack Ove...

android service
Rectangle 27 45

Calling a goto a... goto

What I see in this code is a very creative way to write "goto" with less sulphur-smelling keywords.

There are multiple alternatives to this code, which can or can not be better, depending on the situation.

Your solution is interesting if you have a lot of code, but will evaluate the "exit" of this processing at some limited points:

do
{
   bool isError = false ;

   /* some code, perhaps setting isError to true */
   if(isError) break ;
   /* some code, perhaps setting isError to true */
   if(isError) break ;
   /* some code, perhaps setting isError to true */
}
while(false) ;

// some other code

The problem is that you can't easily use your "if(isError) break ;" is a loop, because it will only exit the inner loop, not your do/while block.

And of course, if the failure is inside another function, the function must return some kind of error code, and your code must not forget to interpret the error code correctly.

I won't discuss alternatives using ifs or even nested ifs because, after some thinking, I find them inferior solutions than your own for your problem.

Perhaps you should put clearly on the table the fact you're using a goto, and document the reasons you choose this solution over another.

At least, it will show something could be wrong with the code, and prompt reviewers to validate or invalidate your solution.

You must still open a block, and instead of breaking, use a goto.

{
   // etc.
   if(/*some failure condition*/) goto MY_EXIT ;
   // etc.

   while(/* etc.*/)
   {
      // etc.
      for(/* etc.*/)
      {
         // etc.
         if(/*some failure condition*/) goto MY_EXIT ;
         // etc.
      }
      // etc.
      if(/*some failure condition*/) goto MY_EXIT ;
      // etc.
   }

   // etc.
}

MY_EXIT:

// some other code

This way, as you exit the block through the goto, there is no way for you to bypass some object constructor with the goto (which is forbidden by C++).

This problem solves the process exiting from nested loops problem (and using goto to exit nested loops is an example given by B. Stroustrup as a valid use of goto), but it won't solve the fact some functions calls could fail and be ignored (because someone failed to test correctly their return code, if any).

Of course, now, you can exit your process from multiple points, from multiple loop nesting depth, so if it is a problem...

If the code is not supposed to fail (so, failure is exceptional), or even if the code structure can fail, but is overly complex to exit, then the following approach could be clearer:

try
{
   // All your code
   // You can throw the moment something fails
   // Note that you can call functions, use reccursion,
   // have multiple loops, etc. it won't change
   // anything: If you want to exit the process,
   // then throw a MyExitProcessException exception.

   if(/* etc. */)
   {
      // etc.
      while(/* etc.*/)
      {
         // etc.
         for(/* etc.*/)
         {
            // etc.
            if(/*some failure condition*/) throw MyExitProcessException() ;
            // etc.
         }
         // etc.

         callSomeFunction() ;
         // the function will throw if the condition is met
         // so no need to test a return code

         // etc.
      }
      // etc.
   }

   // etc.
}
catch(const MyExitProcessException & e)
{
   // To avoid catching other exceptions, you should
   // define a "MyExitProcessException" exception
}

// some other code

If some condition in the code above, or inside some functions called by the code above, is not met, then throw an exception.

This is somewhat weightier than your do/while solution, but has the same advantages, and can even abort the processing from inside loops or from inside called functions.

Your need seems to come from the fact you can have a complex process to execute (code, functions calls, loops, etc.), but you want to interrupt it over some condition (probably either failure, or because it succeeded sooner than excepted). If you can rewrite it in a different way, you should do it. But perhaps, there is no other way.

If you can code it with a try/catch, do it: To interrupt a complex piece of code, throwing an exception is the right solution (the fact you can add failure/success info inside your exception object should not be underestimated). You will have a clearer code after that.

Now, if you're in a speed bottleneck, resolving your problem with thrown exceptions as an exit is not the fastest way to do it.

No one can deny your solution is a glorified goto. There won't be a goto-spaghetti code, because the do/while won't let you do that, but it is still a semantic goto. This can be the reasons some could find this code "bad": They smell the goto without finding its keyword clearly.

In this case (and in this performance, profiled-verified) case only, your solution seems Ok, and better than the alternative using if), but of lesser quality (IMHO) than the goto solution which at least, doesn't hide itself behind a false loop.

As far as I am concerned, I find your solution creative, but I would stick to the thrown exception solution.

So, in order of preference:

Just the effort of such a details answer deserves to be Accepted. I agree on your points on not being able to break out of the inner loops. Failed functions return code still can be stored, if you use integer instead of bool as break condition (like all values > 0 indicate errors)

I would put non-nested ifs as number 2, but otherwise agree.

In java I would use Exceptions in that case without hesitation, but in C++ I somehow careful with using exceptions everywhere. But in that case I now tend to actually use them. Thanks,

Well argued, but I dispute that "To interrupt a complex piece of code, throwing an exception is the right solution." You've made your case for "GOTO" but I would argue that exceptions are semantically linked to, well, exceptional cases. Not to the complexities of control flow.

An easy and clean way to resolve this is to just put the "fake loop" code into a function that is called. You exit the function (via return) when you are done with the logic.

c++ - Do you consider this technique "BAD"? - Stack Overflow

c++ coding-style
Rectangle 27 58

I solved it with "addFlags" instead of "setFlags"

myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Add additional flags to the intent (or with existing flags value).

Be aware if you are using flags that you change history stack as Alex Volovoy's answer says:

...avoid setting flags as it will interfere with normal flow of event and history stack.

I have a very similar problem. Have you experienced any problems with the history stack or anything else as the answers above sugggest?

I'm not exactly sure what you're looking for but you can start an activity without a history like that: Intent intent = new Intent(Intent.ACTION_VIEW, "http:\\www.google.com"));intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(intent);

Thank you. I was doing the same exact thing.

android - Calling startActivity() from outside of an Activity context ...

android android-activity android-context
Rectangle 27 51

Drawable image = context.getResources().getDrawable( R.drawable.ic_action );
int h = image.getIntrinsicHeight(); 
int w = image.getIntrinsicWidth();   
image.setBounds( 0, 0, w, h );
button.setCompoundDrawables( image, null, null, null );
EditText#setCompoundDrawablesWithIntrinsicBounds

Can you provide a source for that? All the documentation I've seen indicates this has been available since API 1.

android - Calling setCompoundDrawables() doesn't display the Compound ...

android android-layout android-drawable
Rectangle 27 37

Calling a function on an object

Consider the following function:

function foo() {
    console.log("bar");
    console.log(this);
}
foo(); // calling the function

Note that we are running this in the normal mode, i.e. strict mode is not used.

When run in a browser, the value of this would be logged as window. This is because window is the global variable in a web browser's scope.

If you run this same piece of code in an environment like node.js, this would refer to the global variable in your app.

Now if we run this in strict mode by adding the statement "use strict"; to the beginning of the function declaration, this would no longer refer to the global variable in either of the envirnoments. This is done to avoid confusions in the strict mode. this would, in this case just log undefined, because that is what it is, it is not defined.

In the following cases, we would see how to manipulate the value of this.

There are different ways to do this. If you have called native methods in Javascript like forEach and slice, you should already know that the this variable in that case refers to the Object on which you called that function (Note that in javascript, just about everything is an Object, including Arrays and Functions). Take the following code for example.

var myObj = {key: "Obj"};
myObj.logThis = function () {
    // I am a method
    console.log(this);
}
myObj.logThis(); // myObj is logged

If an Object contains a property which holds a Function, the property is called a method. This method, when called, will always have it's this variable set to the Object it is associated with. This is true for both strict and non-strict modes.

Note that if a method is stored (or rather, copied) in another variable, the reference to this is no longer preserved in the new variable. For example:

// continuing with the previous code snippet

var myVar = myObj.thisMethod;
myVar();
// logs either of window/global/undefined based on mode of operation
var el = document.getElementById('idOfEl');
el.addEventListener('click', function() { console.log(this) });
// the function called by addEventListener contains this as the reference to the element
// so clicking on our element would log that element itself

Consider a constructor function in Javascript:

function Person (name) {
    this.name = name;
    this.sayHello = function () {
        console.log ("Hello", this);
    }
}

var awal = new Person("Awal");
awal.sayHello();
// In `awal.sayHello`, `this` contains the reference to the variable `awal`

How does this work? Well, let's see what happens when we use the new keyword.

  • Calling the function with the new keyword would immediately initialze an Object of type Person.
  • The constructor of this Object has its constructor set to Person. Also, note that typeof awal would return Object only.
  • This new Object would be assigned the protoype of Person.prototype. This means that any method or property in the Person prototype would be available to all instances of Person, including awal.
  • The function Person itself is now invoked; this being a reference to the newly constructed object awal.

Note that the official ECMAScript spec no where states that such types of functions are actual constructor functions. They are just normal functions, and new can be used on any function. It's just that we use them as such, and so we call them as such only.

function
Objects

All functions inherit from the global Function, and two of its many methods are call and apply, and both can be used to manipulate the value of this in the function on which they are called.

function foo () { console.log (this, arguments); }
var thisArg = {myObj: "is cool"};
foo.call(thisArg, 1, 2, 3);

This is a typical example of using call. It basically takes the first parameter and sets this in the function foo as a reference to thisArg. All other parameters passed to call are passed to the function foo as arguments. So the above code will log {myObj: "is cool"}, [1, 2, 3] in the console. Pretty nice way to change the value of this in any function.

apply is almost the same as call accept that it takes only two parameters: thisArg and an array which contains the arguments to be passed to the function. So the above call call can be translated to apply like this:

foo.apply(thisArg, [1,2,3])

Note that call and apply can override the value of this set by dot method invocation we discussed in the second bullet. Simple enough :)

bind is a brother of call and apply. It is also a method inherited by all functions from the global Function constructor in Javascript. The difference between bind and call/apply is that both call and apply will actually invoke the function. bind, on the other hand, returns a new function with the thisArg and arguments pre-set. Let's take an example to better understand this:

function foo (a, b) {
    console.log (this, arguments);
}
var thisArg = {myObj: "even more cool now"};
var bound = foo.bind(thisArg, 1, 2);
console.log (typeof bound); // logs `function`
console.log (bound);
/* logs `function () { native code }` */

bound(); // calling the function returned by `.bind`
// logs `{myObj: "even more cool now"}, [1, 2]`

See the difference between the three? It is subtle, but they are used differently. Like call and apply, bind will also over-ride the value of this set by dot-method invocation.

Also note that neither of these three functions do any change to the original function. call and apply would return the value from freshly constructed functions while bind will return the freshly constructed function itself, ready to be called.

Sometimes, you don't like the fact that this changes with scope, specially nested scope. Take a look at the following example.

var myObj = {
    hello: function () {
        return "world"
        },
    myMethod: function () {
        // copy this, variable names are case-sensitive
        var that = this;
        // callbacks ftw \o/
        foo.bar("args", function () {
            // I want to call `hello` here
            this.hello(); // error
            // but `this` references to `foo` damn!
            // oh wait we have a backup \o/
            that.hello(); // "world"
        });
    }
  };

In the above code, we see that the value of this changed with nested scope, but we wanted the value of this from the original scope. So we 'copied' this to that and used the copy instead of this. Clever, eh?

  • What if we call the function as a method with Object-dot notation?
  • What if we use the new keyword?
  • How do we manipulate this with call and apply?
bind
this

Why is there a section about the new keyword? Also this question has been beat to death, but we all have "that time we tried to ride the coat-tails of a question answered 4 years ago"

javascript - How does the "this" keyword work? - Stack Overflow

javascript this
Rectangle 27 49

For Multiple Instance of the same activity , use the following snippet,

Activity
AndroidManifest
android:launchMode="singleTop|singleInstance"
android:launchMode="standard"
Intent i = new Intent().setClass(mActivity.getApplication(), TestUserProfileScreenActivity.class);  
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

// Launch the new activity and add the additional flags to the intent
mActivity.getApplication().startActivity(i);

This works fine for me. Hope, this saves times for someone. If anybody finds a better way, please share with us.

Please understand the difference between setFlags() and addFlag() methods. All you are doing now is launching an activity with FLAG_ACTIVITY_NEW_TASK. As in the code posted by Cristian below.

android - Calling startActivity() from outside of an Activity? - Stack...

android alarmmanager android-pendingintent runtimeexception