How to install NativeScript to build Native IOS and Android Mobie Applications ?

What is NativeScript :
It is open source mobile framework. By using NativeScript we can build truly native iOS and Android mobile apps. 
You can get 100% native API access with Javascript, TypeScript or Angular.

Requirements of NativeScript :
  • Latest copy of Java installed on System.
  • Installing Android Studio can be a benefit.

Installing NativeScript :
To install NativeScript use following steps :

Step 1: Install latest Node.js 
Download and install Node JS from following website :
Step 2: Install NativeScript CLI
Open Terminal or Command Prompt and type in following command :

npm install -g nativescript
After Installation we have tns (Telerik Native Scrpt) command on our terminal.

Step 3: Including Android SDK
To run Android projects we require android sdk to be installed on our system. If you already have android studio installed its great. You can use sdk in android studio to run NativeScript Project.
This is the most important part of installation of NativeScript do it carefully you will succeed.
To include android sdk do the following :
On Windows :
  1. Click on Start
  2. Right click on My Computer
  3. Select Properties
  4. If you are in Windows 7 click on Advanced system settings
  5. System Properties Dialog box opens up
  6. Click on Enviornment Variables
  7. Enter ANDROID_HOME path as your Android SDK path as shown in below images
1.  Advanced System Settings :

2. Environment Variable :

3. Android Home path of SDK :

4.Check whether Java Path is correctly installed :

Step 4: Check whether NativeScript Installed Successfully
To check NativeScript is installed correctly with all aspect we need to run this command on our terminal/ command prompt.
tns doctor
If this command returns error please check the SDK location and Java home is correctly specified in enviornment variable.
Java home is shown in following image :

Once you have installed successfully you will find this output on your terminal after tns doctor command and yeh! you are ready to make great mobile applications. Congratulations !


Thank you.
If you installed nativescript using this tutorial please like, share and comment.

Nativescript UI Basics : How to implement Nativescript CardView, GridLayout and Label ?

UI basics of NativeScript :
In order to increase the look and feel of your mobile application, we need to use some good native apis available for Nativescript. One of majorly used component of UI is CardView.
CardView improves UI design to a major extend as you might have experienced in Android Development.
In this tutorial,
  We will learn about Gridlayout, CardView and Label NativeScript Components.
GridLayout is type of container which holds any component in NativeScript. You can find more such containers layouts at NativeScript Official Website.
CardView is beautiful component with shadow. CardView looks more beautiful with Ripple Effect which will be implemented in next tutorial.

Lets get started,

Step 1: Install CardView 
To install CardView in your Nativescript project type following command in your terminal/cmd :
tns plugin add nativescript-cardview
Hardly takes 5 seconds to install.

Step2: Import CardView and Label in your Project
Go to app.component.ts file in your project and add this following code
import * as elementRegistryModule from 'nativescript-angular/element-registry';
import * as LabelModule from "tns-core-modules/ui/label";
elementRegistryModule.registerElement("CardView", () => require("nativescript-cardview").CardView);


Once we have imported the Cardview and Label we can use it in this component.
Step 3: Using CardView in Layout
Now we can use cardview in layout. Here we have not created separate file for layout in order to make this tutorial more simple as possible.
Here we are using GridLayout to explain the concept of using container and Cardview in action.
Copy following code into app.component.ts(Component) template attribute as shown in below image:
<actionbar class="action-bar" title="My App"></actionbar>
    <!-- GridLayout with CardView and Label NativeScript -->
    <gridlayout columns="*,2*" height="100%" padding="5" rows="2*,1*,2*" style.backgroundcolor="lightgray" width="100%" xmlns:card="nativescript-cardview">
      
      <card:cardview col="0" elevation="10" marginright="5" radius="5" row="0">
      <label style.verticalalignment="center" text="Row 0 Col 0">
      </label></card:cardview>
      <card:cardview col="1" elevation="10" radius="5" row="0">
      <label style.verticalalignment="center" text="Row 0 Col 1">
      </label></card:cardview>

      <card:cardview col="0" colspan="2" elevation="10" marginbottom="5" margintop="5" radius="5" row="1">
      <label style.verticalalignment="center" text="Row 1 Col 0 with ColSpan = 2">
      </label></card:cardview>

      <card:cardview col="0" elevation="10" marginright="5" radius="5" row="2">
      <label style.verticalalignment="center" text="Row 2 Col 0">
      </label></card:cardview>
      <card:cardview col="1" elevation="10" radius="5" row="2">
      <label style.verticalalignment="center" text="Row 2 Col 1">
      </label></card:cardview>
    
    </gridlayout>


Lets us see how GridLayout is working to arrange these 5 CardViews in layout. Grid means rows and columns.As you can see in the code we have declared rows="2*,1*,2*" and columns="*,2*"



rows="2*,1*,2*" : Here device screen is divided into 3 rows.
                  Calculate the region size i.e. 2* + 1* + 2* = 5*.
                  If we consider screen height is 500pixels. 
                  Then 2* = 2 X (screenheight / 5) = 2 * 100 = 200 pixels.
                  Similarly, 1* equals 1 X (screenheight / 5) = 1 * 100 =100 pixels.
                  In this way, Screen size is divided across any screen size and density.

columns="*,2*"  : Here device screen is divided into 2 columns. Where * means 1*. 
                  If we consider screen width is 300 pixels. 
                  Then 1* =1 X (screenwidth / 3) = 1 X 100 =100 pixels.
                  So, first column is 100 pixels. 
                  Similarly for 2* = 2 X (screenwidth / 3) = 2 X 100 =200 pixels.
                  Remaining 200 pixels is occupied by second column. 

You can also add style for label :
 styles:[`
  Label{
    text-align:center;
    font-size: 18;
  }
  `]


Now, Run the project using following command in terminal/cmd :
Android :
tns run android
IOS :
tns run ios

Output :

Hope you learnt from tutorial.
Thank you. Comment and share with your best friends.

How to send data using http post request to server using NativeScript ?


What is NativeScript ?
NativeScript is Open Source framework for building truly native mobile apps using Angular, TypeScript or JavaScript.
NativeScript currently supports apps for Android and IOS platforms.
Its is easy to learn, provides good support to easily accessing Native API's both in Android and IOS.
I consider you have installed Nativescript Successfully.

Lets get started,

Step 1: Create Project 
To create Nativescript project type following code into your terminal or cmd(Command Prompt)

tns create PostRequest --template nativescript-template-ng-tutorial
You can also create CreateProject.bat file to use it each time you create project :
set /p input="Enter Project Name : "

tns create %input% --template nativescript-template-ng-tutorial

pause

Step 2: Import Http Module
After creating project open project in Visual Studio Code(Editor with good support for nativescript).
Go to app->app.module.ts file add following code in imports :
import { NativeScriptHttpModule } from "nativescript-angular";

Also add to Module imports as shown here :

Step 3: Add http utility file to your Project 
To perform http post request to server from nativescript application you can use this utility file which will save your time.
Place this file into services folder for better arrangement of folder structure :
Go to your Nativescript Project and create new file into services folder named user.services.ts
Copy paste following code :

import { Injectable } from "@angular/core";
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Observable as RxObservable } from "rxjs/Observable";
import "rxjs/add/operator/map";

@Injectable()
export class UserService {

  // private serverUrl = "https://httpbin.org/post";
  constructor(private http: Http) {}
  postData(data: any)
  {
    let options = this.createRequestOptions();
        return this.http.post("http://IPAddress/XamppProject/testRequest.php",{ data } , options)
            .map(res =>  res.json());
  }

   private createRequestOptions() {
        let headers = new Headers();
        headers.append("AuthKey", "my-key");
        headers.append("AuthToken", "my-token");
        headers.append("Content-Type", "application/json");
        let options = new RequestOptions({ headers: headers });
        return options;
    }
}

Step 4: Using utility file to send post request to server
Finally we will use the utility file and send post request to server. You can import UserService class into any component of your application, for now we will import it in app.component.ts file.
In app->app.component.ts import the UserService class we just created in step 3.
import { UserService } from "./services/user.service";

Include UserService as Providers in component as shown here :

In the image :
1 : Import UserService which is exported class.
2 : Include UserService as Provider to this Component.
3 : Perform Post request to specified Server.
To perform post request insert this code in app.component.ts as shown above :
    userService.postData({LeaderId:"1"}).subscribe((res) => {
      alert(res);
    }, 
    (err)=>console.log("Something went wrong "+err)
    );

So here we complete application side coding. Now lets create PHP file on Server to get data sent from NativeScript Application.
Just add following code in testRequest.php file created on server xampp Project(http://localhost/MyProject/testRequest.php)
 $data = file_get_contents("php://input");
 echo json_encode($data);

Run Project by entering this command in terminal/cmd :
Android :
tns run android
IOS :
tns run ios

Now, just go ahead and test your project and leave some comments and share my post.

Get all files of project here :  GitHub Link

How to show introscreens in android app when app is opened first time



To download app click on : Check out App


Custom In-App intro guide screens for Android :

Main idea behind in app intro guide screen is to make activity background transparent with some alpha and customizing look as you want.


Step 1 : Download Layout file : 


activity_introscreen.xml


Step 2: Edit your Manifest.xml file :


  <activity android:name=".IntroScreenActivity"

            android:theme="@style/Theme.Transparent"/>



Step 3 : Add code in res - styles.xml file


 <style name="Theme.Transparent" parent="Theme.AppCompat.Light.NoActionBar">

        <item name="android:windowIsTranslucent">true</item>

        <item name="android:statusBarColor">@android:color/transparent</item>

        <item name="android:windowBackground">@android:color/transparent</item>

  </style>


We are done with setting up introscreen you can run and see output and add which ever design you like.

You can finish introscreen activity once user clicks on it.

To make it more Cool :

You can add fade out animation on click of introscreen as follows :

Step 1: Create Animation file in anim package :fade_in.xml


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

<alpha xmlns:android="http://schemas.android.com/apk/res/android"

           android:interpolator="@android:anim/accelerate_interpolator"

           android:fromAlpha="0.0" android:toAlpha="1.0"



           android:duration="500" />


Step 2: Create Animation file for closing effect : fade_out.xml


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

<alpha xmlns:android="http://schemas.android.com/apk/res/android"

           android:interpolator="@android:anim/accelerate_interpolator"

           android:fromAlpha="1.0" android:toAlpha="0.0"

           android:fillAfter="true"



           android:duration="500" />



Step 3: Add this code when starting your introscreen activity :


Intent i = new Intent(this, IntroScreenActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);



If you want your introscreen to be only launched first time user opens app  you can use sharedPreference to store app opened status.

Download SharedPreference Util file :


SharedPreference.java

Copy paste code into your first homescreen Activity :


        SharedPreference spre=new SharedPreference(getApplicationContext());
        String show=spref.getData("IntroShown");
        if(show==null){
            Intent intent=new Intent(getApplicationContext(),IntroScreenActivity.class);
            startActivity(intent);
        }
        spref.setData("IntroShown","Yes");



Thank you
Share and Comment





Popup date picker or time picker dialog on click of edittext or any view in Android.




Simple Step by Step tutorial on adding DatePicker and TimePicker in Android :

Step 1 : Include Library in Apps "build.gradle"
compile 'com.wdullaer:materialdatetimepicker:3.0.0'


Step 2 : Declare and Initialize DatePicker and TimePicker :
        //Declaration of Datetimepicker and timepicker dialog
        TimePickerDialog tpd;
        DatePickerDialog dpd;

        //Definition of Datetimepicker and timepicker dialog place in onCreate()
        tpd = TimePickerDialog.newInstance(
                 new TimePickerListener(),
                now.get(Calendar.HOUR),
                now.get(Calendar.MINUTE),
                false
        );
        dpd = DatePickerDialog.newInstance(
                 new DatePickerListener(tv_event_date_from,tv_event_date_to),
                now.get(Calendar.YEAR),
                now.get(Calendar.MONTH),
                now.get(Calendar.DAY_OF_MONTH)
        );

       //To Open Datepicker dialog call this function as follows
       dpd.show(getFragmentManager(), "AnyTag");

       //To Open TimePicker dialog call this function as follows
       tpd.show(getFragmentManager(), "AnyTag");



Step 3 : Creating Listener
//Create a new Listener Class to manage clicks

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

public class DatePickerListener implements  DatePickerDialog.OnDateSetListener {

    TextView from,to;

    public DatePickerListener(TextView from, TextView to){
        this.from=from;
        this.to=to;
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        String tag=view.getTag();
        
         if(tag.equals("from")){
            from.setText(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
            OrderHistoryActivity.datefrom=year+"-"+(monthOfYear+1)+"-"+dayOfMonth;
        }else{
            to.setText(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
            OrderHistoryActivity.dateto=year+"-"+(monthOfYear+1)+"-"+dayOfMonth;
        }
    }
}


//Create a new Listener Class to manage timepicker clicks

import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;

public class TimePickerListener implements  TimePickerDialog.OnTimeSetListener {

    public TimePickerListener(){
    }

     @Override
    public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
        String format;
        if (hourOfDay == 0) {

            hourOfDay += 12;

            format = "AM";
        }
        else if (hourOfDay == 12) {

            format = "PM";

        }
        else if (hourOfDay > 12) {

            hourOfDay -= 12;

            format = "PM";

        }
        else {
            format = "AM";
        }

        String time = hourOfDay+":"+minute+":0"+second+" ";
 
    }
}


Thank You for your Visit +1 and Comment down.

Creating Shopping cart in android : Step by Step tutorial




Shopping Cart is most important feature of all Ecommerce Apps.
Here,
I introduce you with simplest and Customisable Shopping Cart System.

Following is Step By Step Details of implementation :

Step 1 : Create new Activity and Copy this into Layout file : activity_cart.xml

<RelativeLayout android:background="#e1e1e1"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:id="@+id/layout_total"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:padding="5dp"
        android:weightSum="2">
        <TextView android:gravity="end"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:text="Total : "
            android:textSize="20dp">
        </TextView>

        <TextView
            android:id="@+id/tv_total"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:text="0 Rs"
            android:textSize="20dp">
        </TextView>
    </LinearLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_cart"
        android:layout_above="@+id/btn_placeorder"
        android:layout_below="@+id/layout_total"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    </android.support.v7.widget.RecyclerView>


    <Button
        android:id="@+id/btn_placeorder"
        android:layout_gravity="center"
        android:layout_alignParentBottom="true"
        android:layout_height="60dp"
        android:layout_width="match_parent"
        android:onClick="insertOrder"
        android:text="Place Order"
        android:textColor="@android:color/white"
        android:theme="@style/Theme.MaterialButton">
    </Button>

</RelativeLayout>



Copy button style into style.xml in res->val->style.xml

    <style name="Theme.MaterialButton" parent="AppTheme">
        <item name="colorAccent">@color/colorAccent</item>
        <item name="colorButtonNormal">@color/colorPrimaryDark</item>
        <item name="colorControlHighlight">@color/colorAccent</item>
    </style>

Download Images and Put it into your Drawable package :






Step 2 : Copy this into corresponding Java Activity File:



public class CartActivity extends AppCompatActivity {

    RecyclerView recycler_itemlist;
    public static TextView tv_total;
    CartListAdapter cartListAdapter;
    public static int total=0;
    String jsonCartList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        //Set back button to activity
        android.support.v7.app.ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setTitle("Cart");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        tv_total =(TextView) findViewById(R.id.tv_total);

        recycler_itemlist =(RecyclerView) findViewById(R.id.recycler_cart);
        recycler_itemlist.setHasFixedSize(true);
        recycler_itemlist.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        recycler_itemlist.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false));
        recycler_itemlist.getRecycledViewPool().setMaxRecycledViews(0, 0);

        cartListAdapter = new CartListAdapter(CartActivity.this,ItemListAdapter.selecteditems);
        recycler_itemlist.setAdapter(cartListAdapter);

        getIntentData();

        calculateTotal();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; goto parent activity.
                this.finish();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void getIntentData(){
        if(getIntent()!=null && getIntent().getExtras()!=null){
           // Get the Required Parameters for sending Order to server.
        }
    }

    public static void calculateTotal(){
        int i=0;
        total=0;
        while(i<ItemListAdapter.selecteditems.size()){
            total=total + ( Integer.valueOf(ItemListAdapter.selecteditems.get(i).getRate()) * Integer.valueOf(ItemListAdapter.selecteditems.get(i).getQuantity()) );
            i++;
        }
        tv_total.setText(""+total);
    }

    public void insertOrder(View view){

            if(total>0){

            Gson gson = new Gson();
            jsonCartList = gson.toJson(ItemListAdapter.selecteditems);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which){
                        case DialogInterface.BUTTON_POSITIVE:
                            //Yes button clicked
                            placeOrderRequest();
                            break;

                        case DialogInterface.BUTTON_NEGATIVE:
                            //No button clicked
                            break;
                    }
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
            builder.setMessage("Do you want to place Order ?").setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

        }else{
                Toast.makeText(CartActivity.this,"No items in Cart !",Toast.LENGTH_LONG).show();
            }


    }


    private void placeOrderRequest(){
       //Send Request to Server with required Parameters
    /*
   jsonCartList - Consists of Objects of all product selected.
    */
    
    }

}


Include gson and retrofit api :


    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'





Step 3 : Copy model class required to capture all attributes of an Item/Product :




public class Item {

    public String ItemId;
    public String ItemName;
    public String Size;
    public String Company;
    public String Rate;

    public String getStatus() {
        return Status;
    }

    public void setStatus(String status) {
        Status = status;
    }

    public String Status;

    public String getQuantity() {
        return Quantity;
    }

    public void setQuantity(String quantity) {
        Quantity = quantity;
    }

    public String Quantity;

    public void setItemId(String ItemId){
        this.ItemId=ItemId;
    }
    public String getItemId(){
        return ItemId;
    }
    public void setItemName(String ItemName){
        this.ItemName=ItemName;
    }
    public String getItemName(){
        return ItemName;
    }
    public void setSize(String Size){
        this.Size=Size;
    }
    public String getSize(){
        return Size;
    }
    public void setCompany(String Company){
        this.Company=Company;
    }
    public String getCompany(){
        return Company;
    }
    public void setRate(String Rate){
        this.Rate=Rate;
    }
    public String getRate(){
        return Rate;
    }

    public String getJsonObject(){
        return "{ItemId:"+ItemId+",ItemName:"+ItemName+",Size:"+Size+",Company:"+Company+",Rate:"+Rate+"}";
    }
}




To create your custom Model class you can prefer my Automation Site :

Model Class Generator




Step 4 : Copy the Sole of Cart, Adding Items:


We need to copy this static List variable into List Adapter used to display our Item / Product

Just copy this line into Recycler or List Adapter so that 
Items can be added into this list and it can be accessed from any where.

 

public static List < item > selecteditems;




You can check if list already contains item to be added like this :


        if(ItemListAdapter.selecteditems.contains(itemobject)){
           //List already contains item
        }else{
            //List does not contains item you can add item here.
            ItemListAdapter.selecteditems.add(itemobject);
        }




Step 5 : Removing Items from Cart :



            ItemListAdapter.selecteditems.remove(item);
            cartListAdapter.notifyDataSetChanged();
            CartActivity.calculateTotal();





Thank You
Please Dont forget to Comment and +1 Post.



Automate update query in php mysql - Tool DataUpdater



Why ? DataUpdater ?

When you want to update a row in database.
For example, Consider your app or web has a User Profile Page and user can edit it when ever he wants.

In this case we will require php service to update specific record in database and if an extra column needs to be updated in future then we need to change our php service as well.

But using DataUpdater we can update columns dynamically without worrying about code.

So,

Lets use DataUpdater

DataUpdater accepts a unique primary key in your table and columns to update as input and updates that specific row. 


After successful execution of DataUpdater it will return status as output in JSON Array of Object format .


Download DataUpdater.php



How to use DataUpdater.php ?
Steps :


1. Just supply your database details into DataUpdater.php and copy DataUpdater.php into your xampp project.


2. Now DataUpdater is ready to run.


3. Now go to your Chrome browser in url section type following


http://localhost/YourProjectName/DataUpdater.php?table=YourTableName&KeyName=PrimaryKeyName&KeyValue=PrimaryKeyValue&ColumnName1=ColumnValue1&ColumnName2=ColumnValue2

Where,

ColumnName1,ColumnName2,..

Denotes column name to be updated in your table.

ColumnValue1, ColumnValue2,

Denotes Values that need to be assigned to specific column in table.


Note: 

There is no limit for ColumnName and Values you can update N number of Columns using DataUpdater.

Replace YourTableName with any table name in your database.

Replace YourProjectName with your project name or folder name.


Thank You
+1 Post and Comment

How to automate delete data from mysql table - DataDeleter.php



Why ? DataDeleter?

When you want to delete a row in database. 
For example, Consider you wanna delete a post created by user and he wishes it to be deleted, then we create PHP service that accepts post id from client and delete row matching that post id into table.

So, 
Why not automate these coding.
Here comes DataDeleter.

DataDeleter accepts a unique primary key in your table as input and delete that row.

After successful execution of DataPutter it will return status as output in JSON Array of Object format .



So, to download DataDeleter.php go to this link below :





How to use DataDeleter.php ?


Steps :


1. Just supply your database details into DataPutter.php and copy DataPutter.php into your xampp project.

2. Edit database details code to point to your database.

3. Now DataDeleter is ready to run.

4. Now go to your Chrome browser in url section type following :


http://localhost/YourProjectName/DataDeleter.php?table=YourTableName&KeyName=PrimaryKeyName&KeyValue=PrimaryKeyValue


Where,

PrimaryKeyName Denotes name of primary key column in your table.

PrimaryKeyValue 
Denotes value of primary key column in your table.


Example would be as follows :

http://localhost/YourProjectName/DataDeleter.php?table=tblTest&KeyName=UserId&KeyValue=22




Hope you like tutorial.
+1 Post and Comment your response