Skip to main content

Issues and Solutions

  • Display text on the basis of condition(boolean flag) in React Native
import React, {Component} from 'react';
import {Text, View} from 'react-native';

class Test extends Component {
this.state = { displaytext : true }
render() {
return (
<View>{this.state.displaytext && <Text> John is a good man </Text>}</View>
)
 }
  }
export default Test;

OR

import React, {Component} from 'react';
import {Text, View} from 'react-native';

class Test extends Component {
this.state = { displaytext : true }
render() {
return (
<View>{this.state.displaytext ? <Text> John is a good man </Text> : null}</View>
)
 }
  }
export default Test;


  • Build debug apk in React Native without server connection
1. Check in the directory project>android>app>src>main if assets folder is there or not, if not create one.
2. Navigate to the project parent directory through command prompt and execute the following command to bundle project assets:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/

3. Navigate one directory ahead by executing the command: cd android
4. Here, hit the following command to build a debug apk: gradlew assembleDebug
5. It is done! you may find the debug apk at project>android>app>build>outputs>apk>debug

  • Angular JS Directive for allowing numbers, one dot and only two decimal places
 var app = angular.module('myApp', []);

    app.controller('MainCtrl', function($scope) {
    });

    app.directive('validNumber', function() {
      return {
        require: '?ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
          if(!ngModelCtrl) {
            return; 
          }

          ngModelCtrl.$parsers.push(function(val) {
            if (angular.isUndefined(val)) {
                var val = '';
            }
            
            var clean = val.replace(/[^0-9\.]/g, '');
            var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
            if(!angular.isUndefined(negativeCheck[1])) {
                negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
                clean =negativeCheck[0] + '-' + negativeCheck[1];
                if(negativeCheck[0].length > 0) {
                clean =negativeCheck[0];
                }
                
            }
              
            if(!angular.isUndefined(decimalCheck[1])) {
                decimalCheck[1] = decimalCheck[1].slice(0,2);
                clean =decimalCheck[0] + '.' + decimalCheck[1];
            }

            if (val !== clean) {
              ngModelCtrl.$setViewValue(clean);
              ngModelCtrl.$render();
            }
            return clean;
          });

          element.bind('keypress', function(event) {
            if(event.keyCode === 32) {
              event.preventDefault();
            }
          });
        }
      };
    });

  • Cordova build ios is either failing or not showing complete build procedure in terminal
Xcode 10 uses modern build system by default. The cordova build system is not compatible with this new build system, thus results in failure or obfuscation of build procedure. To avoid using modern build system, specify --buildFlag="-UseModernBuildSystem=0" . So the new command to be executed will be: 

 cordova build ios --buildFlag="-UseModernBuildSystem=0"

  • Different App Name for Android and iOS in Cordova
In the config.xml, add the name tag under each platform tag, example:

<platform name ="android">
<name> app name android </name>
</platform>
<platform name ="ios">
<name>app name ios</name>
</platform>

IOS would ask to remove and then add platform again while executing cordova build ios  command, do the needful and enjoy!


  • Different CSS for android and iOS with same class name
Prefix .platform-android or .platform-ios before the CSS class name, for example:

.platform-android .myclass {
// some properties
}

.platform-ios .myclass {
// some properties
}

  • Disable Contextmenu in HTML/javascript
Add event oncontextmenu="return false" to HTML Tag.
Example: <p oncontextmenu="return false">This paragraph is right click disabled.<p/>


  • Disable clipboard menu in HTML input textbox on Android/Cordova
Add event ontouchstart="return false" to HTML Tag.
Example: <input type="text" ontouchstart="return false" />

  • Regular expression for alphanumeric only without space
/^([a-zA-Z0-9]+)$/

  • Regular expression for alphanumeric without space with at least one alphabet
/^(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/

  • Regular expression for alphanumeric without space with at least one alphabet and one number
/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/

  • Restrict special characters and spaces in input textbox using AngularJS Directive
Controller:
myapp = angular.module('app', []);
myapp.controller('mainCtrl', function($scope) {
    $scope.username = '';
})


Directive:
myapp.directive('restrictSpecialCharAndSpc', function() {

  return {

    require: 'ngModel',

    restrict: 'A',

    link: function($scope, $element, attrs, modelCtrl) {

      $element.bind('keydown', function(e) {

        if (e.which === 32) {

            e.preventDefault();

        }

    });

      modelCtrl.$parsers.push(function(inputValue) {

        if (inputValue == undefined)

          return ''

        cleanInputValue = inputValue.replace(/[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.@#€£¥₩₽'"÷× ]/gi, '');

        if (cleanInputValue != inputValue) {

          modelCtrl.$setViewValue(cleanInputValue);

          modelCtrl.$render();

        }

        return cleanInputValue;
      });
    }
  }
});

Template:
<body ng-app="myapp" ng-controller="mainCtrl">
<input type="text" restrict-special-char-and-spc ng-model="username" name="userName">
</body>

  • List AVDs (Android Virtual Device) using cmd
Navigate to users>username>AppData>Local>Android>sdk>tools using command line.
Execute the command emulator -list-avds.

  • Launch AVD using cmd
Navigate to users>username>AppData>Local>Android>sdk>tools using command line.
Execute the command emulator -avd <avd name>.


  • Enable internet in Android Emulator
Navigate to users>username>AppData>Local>Android>sdk>tools using command line.
Execute the command emulator -avd <avd name> -dns-server 8.8.8.8,8.8.4.4


  • Disable right click or context menu in HTML
Use event oncontextmenu="return false" in the parent element of HTML form elements.
For Example: <form action="" oncontextmenu="return false;"> </form>

  • Hello World : My first Blackberry App

package com.rim.samples.helloworld;

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;

/*
* Apps that provide a UI
* must extend the UiApplication class.
*/

public class HelloWorld extends UiApplication
{
     public static void main(String[] args)
     {
          //Create a new instance of the app
          //and start the app on the event thread.

          HelloWorld theApp = new HelloWorld();
          theApp.enterEventDispatcher();
     }

     public HelloWorld()
     {
          //Display a new screen.

          pushScreen(new HelloWorldScreen());
     }
}

//Create a new screen that extends MainScreen and provides
//behaviour similar to that of other apps.

final class HelloWorldScreen extends MainScreen
{
     public HelloWorldScreen()
     {
          //Invoke the MainScreen constructor.

          super();

          //Add a title to the screen.

          LabelField title = new LabelField("HelloWorld Sample", LabelField.ELLIPSIS
               | LabelField.USE_ALL_WIDTH);
          setTitle(title);

          //Add the text "Hello World!" to the screen.

          add(new RichTextField("Hello World!"));
     }

     //To display a dialog box to a BlackBerry device user with the text
     //"Goodbye!" when the BlackBerry device user closes the app,
     //override the onClose() method.

     public boolean onClose()
     {
          Dialog.alert("Goodbye!");
          System.exit(0);
          return true;
     }


}



  • Navigate from one screen to another on button click : Blackberry

button.setChangeListener(new FieldChangeListener()
{
    public void fieldChanged(Field field, int context)
          {
           UiApplication.getUiApplication().pushScreen(new NextScreen());
          }
});



  • How to Use Mgwt 2.0 'Pull to Refresh' or Pull Panel

PullPanel pullpanel = new PullPanel();
PullArrowHeader pullarrowheader = new PullArrowHeader();
PullArrowStandardHandler headerHandler = new PullArrowStandardHandler(pullArrowHeader, pullpanel);
headerHandler.setErrorText("Error");
 headerHandler.setLoadingText("Loading");
  headerHandler.setNormalText("pull down");
 headerHandler.setPulledText("release to load");
 headerHandler.setPullActionHandler(new PullActionHandler()
{
 @Override
 public void onPullAction(final AsyncCallback<Void> callback) {


//Perform task

}

});

pullpanel.setHeaderPullhandler(headerHandler);




  • Align Center : HTML Element

-Using CSS : 

.classname {
margin : auto ;
}

-Using HTML Attribute 

Add attribute align="center" to the parent of the Element.



  • Error: Plugin not found or is not a CDVPlugin - iOS with Phonegap

Firstly, check your config.xml file whether it contains all the plugins or not that are used in the project. Normally looks like below example : 


<feature name="Device">
        <param name="ios-package" value="CDVDevice" />
</feature>

Secondly check in Xcode > Build Phase > Compile Sources if your plugin is present their or not, if not then add by clicking + sign.

Hopefully this should resolve your Problem.



  • Android : Install app through CLI

Go to the directory through CLI where .apk file is present and run the following command :

adb install <apk name.apk>

The application will be installed to your device.



  • Android : Uninstall app from the device through CLI

Simply run the following command : 

adb shell pm uninstall <Package name>

The application will be uninstalled from your device.



  • Uncaught Exception : undefined is not an object (evaluating '(qyb(), pyb).a.IF') - Gwt/Mgwt

If you get the exception information like this in the logs, it becomes difficult to identify the bugged code, so in order to save time from debugging the whole code, just follow the mentioned steps : 

1 . Open the POM.xml of the project.

2. Add the tag <style> PRETTY </style> or if it is already their in the file, then just uncomment it.

3. Build and Re - run the project and you will get the decoded logs.



  • Set HTML Div height to 100% with no content using CSS

Setting height value in 'vh' in CSS class, In this case we need to set it to 100 for letting the div to cover full height.

div {

height:100vh;

}


OR


Add following properties to your application CSS file :

html, body {


height : 100%;

margin : 0 ;

padding : 0;

}



  • Phonegap/Cordova : To call a function on orientation change event

Add following piece of code in your application's parent JS file :

window.addEventListener("orientationchange", orientationChange, true);

function orientationChange () {

// Perform Something

}


  • Apply CSS to alternate list items generated dynamically / apply css to odd/even list items generated dynamically

li: :nth-child(2n) {

/* properties for even number of list items */

}

li: nth-child(2n-1) {

/* properties for odd number of list items */

}


  • Align div at the center of another div both horizontally and vertically using flex property in CSS3

HTML:

<div class = "outerdiv>
<div class="innerdiv>Hello World</div>

CSS:

.outerdiv {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content:center;
align-items: center;
}
.innerdiv {
text-align:center;
}


  • Provisioning profile not getting installed/updated in xcode - iOS
Try out the following steps:
  1. Open Keychain Access and delete the desired provisioning profile.
  2. Go to the directory ~/Library/MobileDevice/Provisioning Profiles.
  3. Delete the specific provisioning profile.
  4. Now double click on the provisioning profile that you want to install.
  5. Open Keychain Access and now you can see the newly installed provisioning profile in the list.

  • Free Provisioning profile for testing app on IOS device
  1. From within Xcode 7.x or higher (Mac only), navigate to “Xcode>Preferences>Accounts.” Hit the '+' icon below left to add your Apple ID*. After you add your account, it will show within the main account window on the right.
  2. Select your account, hit the “View Details” button and wait (be patient) for them to load.
  3. Now create the 'signing identity' used to create a provisioning profile used for device testing - Hit the “Create” button next to the 'iOS development' label. When completed, hit ‘Done'.
  4. Connect your device (cable only, not wireless) and select it as build destination via the 'active scheme' dropdown to the right of the play and stop icons.
  5.  In target's 'General' tab/settings:
    * Set app identifier you want for your free profile

    * Set team id as your apple id
    * Hit 'fix issue' button below the provisioning profile warning - You may have to ‘Fix Issue more than once - keep at it so Xcode can step thru them as needed.
    * Run your app with your device selected.

  • Check out npm and node version through terminal
Execute the below respective commands: 

For npm: <npm -version>

For node: <node --version>


  • Cross Origin Request : xmlHttpRequest cannot load file : Chrome issue
Download the chrome extension from here and problem will be resolved.


  • XCode problem: You don’t have permission to save the file ‘iOS DeviceSupport’ in the folder ‘XCode'
Open the terminal app 
Execute the command: sudo chmod 777 /Users/<Account>/Library/Developer/XCode 
Disconnect your device and connect it back 
XCode should now add your device for development


  • Print image through source url (src) in Google Chrome Console
console.log('%c       ', 'font-size: 100px; background: url(<image url>) no-repeat;');


  • Show/hide hidden files in mac OS
Open the terminal
Execute the command <defaults write com.apple.finder AppleShowAllFiles YES> to show.
Execute the command <defaults write com.apple.finder AppleShowAllFiles NO> to hide.
Press Option/alt key, right click on finder icon and hit Relaunch.
You're done!


  • Split .zip file into multiple segments
Go to the zip location through command line or Terminal.
Execute the command zip <filename.zip> --out new.zip -s 15m.
This would create new.zip, new.z01, new.z02 ... each of size 15mb.
To recollect the chunks execute the command zip -F new.zip --out filename.zip
This would recreate filename.zip and you can extract it now!

Comments

  1. Zipalign is not working to align the unsigned apk.

    ibggn0761-l:apk Reetesh1$ cd /Users/reetesh/Library/Android/sdk/build-tools/23.0.3/zipalign -v 4 app-release-unsigned.apk xxx.apk

    ReplyDelete

Post a Comment