I have a requirement where i have to use string from resources in android to support different languages . Switch case is not taking string as constant from resources. Like R.string.example

So i have to use enums.Need an example to use enums constant using string resources in android and using it in Switch case

In my MainActivity, I have the following function:

public void writefile (FileOutputStream fOut, String fileName, OutputStreamWriter osw, String message){
    try {
        fOut = openFileOutput(fileName, MODE_WORLD_READABLE);
        osw = new OutputStreamWriter(fOut);
    catch (IOException ioe){

My SMS receiver for this app MUST be non-dynamic (no layout), and within my onReceive method, I try to call the function:

writefile(fOut, ib1, osw, message);

My parameters are all ok, but 'writefile' becomes red and 'cannot be resolved.' So I tried changing it to:

MainActivity.writefile(fOut, ib1, osw, message);

But now, 'writefile' is underlined with a static/non-static problem. In order to get rid of this error, I tried making the function static in MainActivity, but then, 'openFileOutput' starts to complain about static/non-static.

I was willing to put the function into my Receiver class too to be called every time from the same class, but functions like 'openFileOutput' cannot be resolved because the Receiver can only extend BroadcastReceiver.

I was also willing to call another activity upon onReceiver and do my work there, but I couldn't find a way to implement that either.

Can anybody please offer me any help on this issue? Thanks in advance.

I have about 229 image assets that I am referring to here. I would like to have a grid of all the images shown in an activity. the images are of places. If a place has not been discovered, I want the picture to be a silhouette of the respective image, and if it has been discovered, I want it to show the actual image.

I don't have silhouettes of my images, and I could do them one by one, but that seems a bit ridiculous.

Is there some android/java property or method I can use to 'black' out the image? Or, is there a tool online I can upload a folder of images to that will black them all out, and I can download a zip folder?

On our Android app we need to detect when users have been providing us with fake locations. Once we disable the fake location app ("Fake GPS"), the Fused Location Provider keeps sending us the old location, but without the mock location key on it.

Is this a known bug? Is there any way to detect if those new locations were from the fake provider?

We are using a Nexus 6P with 6.0.1 to test

Parting from the Android Quickstart Firebase Auth sample, is it ok to do the following in onActivityResult after a successfull Google Sign-In?

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == DialogSignInFragment.RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {

            //-------- Is the following call allowed? --------

            GoogleSignInAccount account = result.getSignInAccount();
        } else {
            Log.e(TAG, "GOOGLE SIGN IN FAILED: " + result.toString());

As far as I know, authenticating to Firebase with a Google account is a two step process.

First you sign in into the Google account to retrieve a token, then you use that token to get the credentials so that you can perform a FirebaseAuth.signInWithCredential() call to ultimately sign into firebase.

Is it necessary for any further Firebase operation to remain signed-in with that Google Sign-In process? I'd say no, since you also don't have to remain signed into Facebook for Firebase to continue working, is this assumption correct?

Are there any negative side-effects to doing this? I want to sign out after a successfull sign-in in order to keep the code cleaner. FYI, the following code does successfully sign into Firebase even after that Auth.GoogleSignInApi.signOut() call.

What are the limitations, ie, how long are those credentials valid after signing out? Long enough to be able to sign into Firebase with them, or will a race condition start on Googles servers?

i am trying to send Data (ID value) from one activity to other but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code

public class Order extends AppCompatActivity {

    private ListView lvUsers;
    private ProgressDialog dialog;

protected void onCreate(Bundle savedInstanceState) {
    dialog = new ProgressDialog(this);
    dialog.setMessage("Loading, please wait.....");

    lvUsers = (ListView) findViewById(R.id.lvUsers);
    new JSONTask().execute("");


public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {

    protected void onPreExecute(){

    protected List<OrderModel> doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line ="";
            while ((line=reader.readLine()) !=null){

            String finalJson = buffer.toString();

            JSONArray parentArray = new JSONArray(finalJson);

            List<OrderModel> orderModelList = new ArrayList<>();

            Gson gson = new Gson();
            for (int i = 0; i < parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);
                OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
            return orderModelList;

        }catch (MalformedURLException e) {
        }catch (IOException e) {
        } catch (JSONException e) {
        } finally {
            if(connection !=null) {
            try {
                if (reader !=null) {
            } catch (IOException e) {
        return null;
    protected void onPostExecute(List<OrderModel> result) {
        OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);

public class OrderAdapter extends ArrayAdapter {

    public List<OrderModel> orderModelList;
    private int resource;
    private LayoutInflater inflater;
    public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
        super(context, resource, objects);
        orderModelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;

        if(convertView == null){
            holder = new ViewHolder();
            convertView=inflater.inflate(resource, null);
            holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
        }else {
            holder = (ViewHolder) convertView.getTag();

        final int orderId = orderModelList.get(position).getId();
        holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
        holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                Intent intent = new Intent(Order.this, OrderSelected.class);
                intent.putExtra("parameter_name", orderId);
        return convertView;

    class ViewHolder{
        private Button bOrderNo;


The holder gets executed in loop i guess is why it wouldn't send right Id. How do i get it to send only Id of the clicked orderId

you can check this link to see how json Response looks like

I am creating an application for a boutique. The application should monitor the whatsapp image folder for new images (as a service in the background). When new images arrive (downloaded), the service should read the image and add a 'text' watermark, which shall be the product code of that image, and then save it back in the same file name. Thus when the user opens the image using any application, he shall be able to see the image with product code watermarked in it. The product code shall be a number sequence.

I was thinking writing a service that shall scan the entire whatsapp image folder, and water mark each image. The service should also write some extra metadata as EXIF info, to identify whether an image is already watermarked.

is this possible? How can i do that?

Any help on how to get my recyclerView to stop changing the disabled items on scroll. here is some example code:

public PlayerSelectRVAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    View contactView = inflater.inflate(R.layout....., parent, false);

    ViewHolder viewHolder = new ViewHolder(contactView);
    return viewHolder;

public void onBindViewHolder(PlayerSelectRVAdapter.ViewHolder viewHolder, int position) {
    final Object player = objects.get(position);


public static class ViewHolder extends RecyclerView.ViewHolder {
    private final View mView;
    private Object player;

    public ViewHolder(View itemView) {
        this.mView = itemView;

        mView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (listener != null)
                    listener.onItemClick(mView, getLayoutPosition());

Ok, so in my setPlayer method i am also taking the itemView for that holder and setting if its disabled or not. then i call my SetUi to actually do the view set up.

Thing is it all loads correct until i start scrolling and it messes up. In fact eventually everything becomes disabled.

I am a beginner in the Cordova software but I know this topic has already been investigated upon, however none of the other solutions found so far worked.

So basically what I want to do is to display a google map view on an Android app. I am using Cordova, which provides the cordova-plugin-googlemaps that allows me to use google maps services on a native app.


- Necessary SDK plugins are installed

Google play services is installed. Basically all google plugins present in the SDK manager are installed.

- Created key with Google maps v2 API (Goolge APIs)

Google certificates screenshot

Even after waiting to insert the key in my project past the "5 minutes" Google asks to wait, still nothing.

- Working on iOS but not on Android

Android and iOS

Screenshots of android and ios

- AndroidManifest.xml has API key

Cordova automatically modified the androidManifest.xml and inserted the key (with command: cordova plugin add cordova-plugin-googlemaps --variable API_KEY_FOR_ANDROID="AIz#################################_aE" --variable API_KEY_FOR_IOS="AIz#################################Rns")



    <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AI***********************************aE" />

    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />



- logcat message of Android device says "Authorization failure"

Error message:

E/Google Maps Android API( 8608): Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
E/Google Maps Android API( 8608): In the Google Developer Console (https://console.developers.google.com)
E/Google Maps Android API( 8608): Ensure that the "Google Maps Android API v2" is enabled.
E/Google Maps Android API( 8608): Ensure that the following Android Key exists:
E/Google Maps Android API( 8608):   API Key: AIz#################################_aE
E/Google Maps Android API( 8608):   Android Application (<cert_fingerprint>;<package_name>): 12:################################################C6:F5:41;com.example.mapProj

Authorization failure means there is something wrong with the certificate but nothing seems to be out of place right?

Reinstalling plugins, cleaning caches and creating new projects never worked for me.

I appreciate any help of any kind for this issue. I guess that Cordova can't allow this plugin to be broken on Android so there must be something wrong, it's just that I can't find it


I have an app that mutes the phone by using AudioManager and setting ringer mode to silent with this code:

AudioManager audioManager = 
    (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
try {
} catch (Exception e) {

This works with Android 6, but now with Android 7, I get the following error:

System.err: java.lang.SecurityException: Not allowed to change Do Not Disturb state
System.err: at android.os.Parcel.readException(Parcel.java:1683)
System.err: at android.os.Parcel.readException(Parcel.java:1636)
System.err: at android.media.IAudioService$Stub$Proxy.setRingerModeExternal(IAudioService.java:962)
System.err: at android.media.AudioManager.setRingerMode(AudioManager.java:1022)
System.err: at controllers.SearchResultController.mutePhone(SearchResultController.java:185)

Are there any new permissions I need to ask for to make this work?

I looked through the Android permissions list, but couldn't find any that seemed relevant.

I retrieve state list from my database. I get list in the form of json. I add all state in ArrayList<String>. Now I want to display that complete list of states in AlertDialog using adapter.

But when I set arraylist to adapter and use that adapter in builder.setAdapter(); it displays last item of arraylist i.e only one value from complete arraylist.

I don't know how to do?

below is my code

JSONObject jsonObject = new JSONObject(response.body().string());
Log.d("JSON", String.valueOf(jsonObject));
JSONArray jsonArray = jsonObject.getJSONArray("states");

for(int i=0; i<jsonArray.length(); i++)  {
    stateList = new ArrayList<String>();
    JSONObject jobjstate = jsonArray.getJSONObject(i);

    states = jobjstate.getString("state_name");

    stateAdapter = new ArrayAdapter<String>(UserRegister.this, android.R.layout.simple_spinner_dropdown_item, stateList);

runOnUiThread(new Runnable() {
    public void run() {
        AlertDialog.Builder builder = new AlertDialog.Builder(UserRegister.this);

        View customTitle = View.inflate(getApplicationContext(), R.layout.custom_dialog_state, null);

        builder.setAdapter(stateAdapter, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
        AlertDialog alertDialog = builder.create();
        ListView listView = alertDialog.getListView();
        listView.setDivider(new ColorDrawable(getResources().getColor(R.color.purple)));

I have a RecyclerView that gets touch events. Everything works fine, BUT, when I make Visibility.Visible a LinearLayout (android:clickable="true") above the Recyclerview, and later I make it Visibility.Gone .Then the recyclerView does not gets the touch events. What can I do?

tip_container is the problematic Layout, that swallows RecyclerView touch events when visibility.visible, and even when once shown is visibility.gone.


 <?xml version="1.0" encoding="utf-8"?>




    <FrameLayout android:id="@+id/contenedor" android:layout_width="match_parent"
        android:layout_height="match_parent" />










I am trying to hide the address bar for both iphone and android (if possible) and have seen multiple threads that used the following code snippet as part of their DNN website by inserting the following into their default.aspx file:

    <%-- Add mobile bookmark buttons --%>   
    <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="mobile-web-app-capable" content="yes">

<%-- Set Apple icons. --%>
<asp:placeholder ID="appleIcons" runat="server" />   

        <%-- Set view port for mobile devices. --%>
       <meta name = "viewport" content = "width=device-width" />
        <meta name="viewport" content="width=device-width, minimal-ui">

         <%-- Set Apple icons. --%>
         <link rel="apple-touch-icon" href="/Portals/0/images/apple-touch-icon-114x144.png" />
          <link rel="apple-touch-icon" sizes="72x72" href="/Portals/0/images/apple-touch-icon-114x144.png" />
          <link rel="apple-touch-icon" sizes="114x114" href="/Portals/0/images/apple-touch-icon-114x144.png" />
          <link rel="apple-touch-icon" sizes="144x144" href="/Portals/0/images/apple-touch-icon-114x144.png" />  

         <%-- Remove URL bar on mobile devices. --%>                 
        <script type="application/x-javascript"> 
            addEventListener("load", function() { setTimeout( hideURLbar, 0); }, false); 
            function hideURLbar(){ window.scrollTo(0,1); } 

I have tested all related threads on this topic. The above worked on a site previously albeit only on iphone but no longer working for me. Appreciate any comments.

I am trying to use this code

- (void)textFieldDidBeginEditing:(UITextField *)textField
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25f];
    CGRect frame = self.view.frame;
    frame.origin.y =frame.origin.y -204;
    [self.view setFrame:frame];
    [UIView commitAnimations];

- (void)textFieldDidEndEditing:(UITextField *)textField
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y + 204;
    [self.view setFrame:frame];
    [UIView commitAnimations];

To move view up when keyboard is present but this results like this: enter image description here

becomes this:

enter image description here

Can't figure out why and if it has to do something with the navbar or constraints.

I am using The Amazing Audio Engine to simply play an audio file, but I find that when the channel starts playing, there is some automatic fade in happening.

You can see the top waveform is the output of my iPad, and the bottom waveform is the actual raw audio file. There is definitely a 30ms microfade being done.

enter image description here

There is nothing doing that within the amazing audio engine library, so it's something internally happening from apple's mixer audio unit. Is there any way to turn off this behavior?

I have an UIScrollView and inside this I have an UILabel. I need to detect tap gesture events for the UILabel. At the moment, it' not working. I am new in xamarin IOS, please help. Thanks in advance.

Here is my Code

UILabel lViewallLabel = new UILabel(new CGRect((View.Bounds.Width / 2) - 20, 270, View.Bounds.Width / 2, 16));
lViewallLabel.Text = "VIEW ALL >>";
lViewallLabel.TextAlignment = UITextAlignment.Right;
lViewallLabel.TextColor = UIColor.White;
lViewallLabel.Font = UIFont.SystemFontOfSize(12f);
lViewallLabel.AdjustsFontSizeToFitWidth = true;
lViewallLabel.UserInteractionEnabled = true;
UITapGestureRecognizer tgrLabel2 = new UITapGestureRecognizer(() =>
             UIAlertView myAlert = new UIAlertView();
             myAlert.Message = "Label was tapped.";
             myAlert.Title = "It worked!";


I have a simple test (see below). I would like to run the test with like 6 input values. I could create 6 single methods with 6 datasets, or iterate through 6 setups. While putting everything in it's own method would show me a failure more detailed, the second one would have less redundant code.

Which way is the better one?

    func testValueByStringRange_1(){

    let parser = Parser()
    let input = "22016080120160802ZE0000000000000+RP0000000000000+RF0000000000000-"
    let indexFrom = 19
    let indexTo = 31

    let expected = "000000000000"
    let returnString = parser.valueByStringRange(input, indexFrom: indexFrom, indexTo: indexTo)

    XCTAssertEqual(returnString, expected)

One reason a profile may be invalid according to Developer.Apple.com is that the certificate is now obsolete. Checking for the cert is covered in this post: Validate certificate and provisioning profile

I am interested more generally, how to test if the profile is now stale. Right now I find out with a very long delay, so it is impossible to decipher the cause of the invalidation. If I could run this command, say each time my build job runs on Jenkins, then I could be better able to failure analyze by noting exactly when the shift occurred from valid to invalid.

I've been trying to use UISegmentedControl as a multiple-choice selection tool. I thought that if I could rotate it 90 degrees (as well as the text inside) and expand the cells, it would be a very fluid tool. However no matter what I try it keeps giving me variations of thisbroken UISegmentedControl

By the way, this is inside a UICollectionView. Here is my code for the UICollectionViewCell

class customCollectionCell: UICollectionViewCell {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var questionDescriptionLabel: UILabel!
@IBOutlet weak var viewForSegment: UIView!
var segment: CustomSegmentedControl!

func heightForView(text:String, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.text = text

    return label.frame.height

func loadQuestions(choices: [String], pointIndex: [Int]) {
    segment = CustomSegmentedControl(items: choices)
    segment.transform = CGAffineTransformMakeRotation(CGFloat(M_PI / 2.0));
    for view in segment.subviews {
        for sv in view.subviews {
            if sv.isKindOfClass(UILabel){
                let subview: UILabel = sv as! UILabel
                subview.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI / 2.0))
                subview.addConstraint(NSLayoutConstraint(item: subview,
                    attribute: NSLayoutAttribute.Height,
                    relatedBy: NSLayoutRelation.Equal,
                    toItem: nil,
                    constant: heightForView(subview.text!, width: self.viewForSegment.frame.width)))
                subview.addConstraint(NSLayoutConstraint(item: subview,
                    attribute: NSLayoutAttribute.Width,
                    relatedBy: NSLayoutRelation.Equal,
                    toItem: nil,
                    constant: self.viewForSegment.frame.width))
    segment.pointIndex = pointIndex
    self.addConstraint(NSLayoutConstraint(item: segment, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.LeftMargin, multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: segment, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: segment, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.RightMargin, multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: segment, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: questionDescriptionLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 20))
    segment.frame = CGRect(origin: CGPoint(x: questionLabel.x, y: ), size: segment.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize))

    segment.bounds.size = segment.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize)
    viewForSegment.frame.size = viewForSegment.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize)


I am trying to build an application for users to view Images. For this I use the pixaBay API which returns the following JSON on an API request.

"total": 4692
"totalHits": 500,
"hits": [
        "id": 195893,
        "pageURL": "https://pixabay.com/en/blossom-bloom-flower-yellow-close-195893/",
        "type": "photo",
        "tags": "blossom, bloom, flower",
        "previewURL": "https://pixabay.com/static/uploads/photo/2013/10/15/09/12/flower-195893_150.jpg"
        "webformatWidth": 640,
        "webformatHeight": 360,
        "imageWidth": 4000,
        "imageHeight": 2250,
        "views": 7671,
        "id": 14724,


This is how I implemented the code, to take the previewURLs and load the preview Images on cells with a UICollectionView

     import UIKit
   import Alamofire
   import SwiftyJSON

class ViewController: UIViewController , UICollectionViewDataSource{

@IBOutlet weak var collectionView: UICollectionView!

var newImage : UIImage?
var imageURL : NSURL?
var images:[NSIndexPath: UIImage] = [:]

var previewURL : NSURL? = NSURL()

override func viewDidLoad() {

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 20

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

  let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell


    Alamofire.request(.GET, "https://pixabay.com/api/", parameters: ["key": "31....7f"])
        .responseJSON{ response in
            if let value = response.result.value {

               let hits = JSON(value)["hits"]

                if let previewString = hits[indexPath.row]["previewURL"].rawString(){

                    self.previewURL = NSURL(string: previewString)!

              } else{   print("Error : A previewURL wasn't found.")


            cell.imageView.image = nil //or the placeholder image

            if let img = self.images[indexPath] {
                print("\(img) : \(indexPath)")
                cell.imageView.image = img

            } else {
               self.downloadImage({ (image) in

                    dispatch_async(dispatch_get_main_queue(), {
                        if let img = image {
                            self.images[indexPath] = img

                        } else {

  return cell

func downloadImage(completion: (UIImage?)->Void) {

            if self.previewURL != nil {

                let session = NSURLSession.sharedSession()
                let request = NSURLRequest(URL: previewURL!)
                let task = session.dataTaskWithRequest(request) {data, response, downloadError in

                if let imageData = data  {
                self.newImage = UIImage(data: imageData)
            } else {
    } else {


How should I modify this code so as to load and display the images on a collectionView quickly and sequentially(i.e. one image downloaded and then displayed rather than all downloaded and displayed collectively) ? This implementation takes a heck of a lot of time.

This question already has an answer here:

I can't figure out why am I getting this error while submitting for preview in itunesconnect, the error itself is unhelpful.