Monday, July 29, 2019

Kotlin Introduction and Examples | Kotlin Hello Example | Kotlin For Loop | Kotlin While Loop | Kotlin Array | Android Kotlin


Dear Friends, Now in these days ‘Kotlin’ have been the very popular programming language for software development specially for Android Development so let us have a quick look and then in next Blog/Post we will use it in Android Projects.


Question: What is 'Kotlin'?
Answer: 'Kotlin' is a cross-platform statically typed language developed by JetBrains.

Question: What are the variable types in 'Kotlin'?
Answer: Below are the main variable types in 'Kotlin'-
Characters: 'Kotlin' uses ‘Char’ keyword for Characters. 

Booleans: 'Kotlin' uses ‘booleans’ keyword to represent Booleans which have 2 values true or false.

Number: 'Kotlin' have almost same keywords as Java for Number type- Double, Float, Long, Int, Short, Byte.

Strings: In 'Kotlin' Strings are represented by the 'String' keyword. 

Arrays: In 'Kotlin' Arrays are represented by the Array class, that has get and set functions. We will see some examples in later post. 

Question: How to use/write variables in 'Kotlin'?
Answer: Basically, there are two types of use of variables in 'Kotlin' language –
i)Read only or final variable(define with 'val' keyword)-
val num1: Int = 110 // Int with assignment
val num3: Int // without assignment
val name: String = “Manish” // String type with assignment 

ii)Reassigned variables(define with 'var' keyword)-
var num1: Int = 110 // with assignment
num1 = num1 + 90 // we change the value of Reassigned variables
var num3: Int // without assignment
var num2: 220 // with assignment but without type
var name = “Manish”

Question: how to write 'Kotlin' functions?
Answer: We write 'Kotlin' function with 'fun' keyword and arguments with ':' keyword.

An Example of 'Kotlin' function to add 2 number-

fun sum(num1: Int, num2: Int): Int {
return num1 + num2
}

Question: How to use comment lines in 'Kotlin'?
Answer: It is the same as Java and other programming languages:

i)Single line or End of line comment 
//This is test comment line

ii)Multiline or Block
/*This is multiline test
Comment for 
Kotlin*/

=======Let us take some examples for better understanding======
1)HelloKotlin
class HelloKotlin
/*Kotlin fun with
Androidhub4you.com*/
fun main()
{
println("Hello from Androidhub4you.com")

}

Output: Hello from Androidhub4you.com


2)IfElseKotlin
class IfElseKotlin
/*Kotlin fun with
Androidhub4you.com*/
val num1: Int = 50
val num2: Int = 60
fun main()
{
        if (num1 > num2)
{
         println("num1 is greater than num2")
}
else
{
println("num1 is smaller than num2")
}

}

Output: num1 is smaller than num2



3)WhileLoopKotlin
class WhileLoopKotlin
/*Kotlin fun with
Androidhub4you.com*/
fun main()
{
var start = 1 //use 'var' as we want to do increment on start-varaiable
val max = 10 //use 'val' as we just want to comparaisen with max-varaible
while (start <= max)
{
println(start)
start++
}
}

Output:
1
2
3
4
5
6
7
8
9
10


4)ForLoopKotlin
class ForLoopKotlin
/*Kotlin fun with
Androidhub4you.com*/
fun main()
{
//increment one by one, it will include 15 as well
println("---Increment by 1 number, including till number---")
for (num1 in 10..15)
{
println(num1)
}
//increment one by one, it will include 15 as well
println("---Increment by 1 number, without till number---")
for (num1 in 15 until 20)
{
println(num1)
}
//increment by 2 number
println("---Increment by 2 number---")
for (num1 in 20 until 30 step 2)
{
println(num1)
}
println("---Decrement by 1 number---")
//for loop for decrement
for (num1 in 40 downTo 30)
println(num1) //we can exclude brackets if we want to write single line only
println("---Decrement by 2 number---")
//for loop for decrement
for (num1 in 50 downTo 40 step 2)
{
println(num1)
}

}

Output:
---Increment by 1 number, including till number---
10
11
12
13
14
15
---Increment by 1 number, without till number---
15
16
17
18
19
---Increment by 2 number---
20
22
24
26
28
---Decrement by 1 number---
40
39
38
37
36
35
34
33
32
31
30
---Decrement by 2 number---
50
48
46
44
42
40


5)ArrayKotlin
class ArrayKotlin
/*Kotlin fun with
Androidhub4you.com*/
fun main()
{
//use listOf keyword to store array elements
val arrayCountry = listOf("Germany", "USA", "UK", "Sweden")
//use for loop to print all elements in array
for(country in arrayCountry)
println(country)
//let us take one more example, how to create array of numbers using toList keyword
val arrayNumbers = (50..60).toList()
for (num in arrayNumbers)
println(num)

}

Output:
Germany
USA
UK
Sweden
50
51
52
53
54
55
56
57
58
59
60

Note: In order to run Kotlin programmes you may use Eclipse with Kotlin-Plugin or use IntelliJ-IDE. Let me know if need more assistance.

Thanks,
Manish

Sunday, January 31, 2016

Android Material Design Demo | Android Lolypop Material Design Example | Material Design Collaps Layout | Material Design SnackBar

Hello Friends,
Here a useful example for android material design, important steps are given below-

1)Create a new android project using visual studio.
2)open your build.gradle file from src folder and import below dependencies-
compile 'com.android.support:design:22.2.1'compile 'com.android.support:cardview-v7:22.2.1'
 
  
3) And now import full code from GIT-HUB and modify according to your use-

https://github.com/manishsri01/MaterialDesign

 




Important Code:
1)Calling fragments from navigation drawer-
@Overridepublic void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments  
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    switch (position) {

        case 0:
            FloatingFragment homeFragment = new FloatingFragment();
            transaction.replace(R.id.container, homeFragment);
            transaction.commit();
            break;
        case 1:
            SnackBarFragment snackbar = new SnackBarFragment();
            transaction.replace(R.id.container, snackbar);
            transaction.commit();
            break;
        case 2:
            CollapsFragment collasps = new CollapsFragment();
            transaction.replace(R.id.container, collasps);
            transaction.commit();
            break;

    }
}
 
2)Ssnackbar action-
 
package com.android.materialdesign.fragment;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.materialdesign.R;

public class SnackBarFragment extends Fragment {

   @Override   public void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub      super.onCreate(savedInstanceState);
   }

   @Override   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                      Bundle savedInstanceState) {

      final View v = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_snackbar,
            container, false);

      FloatingActionButton fab = (FloatingActionButton)v.findViewById(R.id.fab);
      fab.setOnClickListener(new View.OnClickListener() {
         @Override         public void onClick(View view) {
            Snackbar.make(v.findViewById(R.id.coordinatorLayout), "I am a Snackbar", 
                 Snackbar.LENGTH_LONG).setAction("Action", new View.OnClickListener() {
               @Override               public void onClick(View v) {
                  Toast.makeText(getActivity(), "Snackbar Action", Toast.LENGTH_LONG).show();
               }
            }).show();
         }
      });

      return  v;
   }

}


 3)Floating point-

package com.android.materialdesign.fragment;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.materialdesign.R;

public class FloatingFragment extends Fragment {

   @Override   public void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub      super.onCreate(savedInstanceState);
   }

   @Override   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                      Bundle savedInstanceState) {

      View v = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_floating,
            container, false);
      FloatingActionButton fab = (FloatingActionButton)v.findViewById(R.id.fab);

      fab.setOnClickListener(new View.OnClickListener() {
         @Override         public void onClick(View view) {
            Toast.makeText(getActivity(),"work in progress..",Toast.LENGTH_SHORT).show();
         }
      });

      return  v;
   }

}


DOWNLOAD ZIP CODE

Thanks,
Manish

Monday, December 28, 2015

PHP Web-Services to Return JSON Array | PHP Web services | Simple JSON Array web services




<?php
//open database connection
$con = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('mydb',$con);

//make a sql query to store data
$sql="SELECT * from `mydb`.`user`";
$qur=mysql_query($sql);

//check the database response is it true or false
 if($qur){
 if (mysql_num_rows($qur)>0) {
//write data into json array
$info = array();

while ($row = mysql_fetch_assoc($qur))
{
     $arr = array();
     $arr["name"] = $row["name"];
     $arr["email"] = $row["email"];
     $info[] = $arr;
}

$json=array("status"=>1,"message"=>"done","result"=>$info);

}
else{
$json=array("status"=>0,"message"=>"No Record found!");
}
}
else{
$json=array("status"=>0,"message"=>"error");
}


OutPut:

{
    "status": 1,
    "message": "done",
    "result": [
        {
            "name": "manish",
            "email": "[email protected]"
        },
        {
            "name": "Test",
            "email": "[email protected]"
        }      
 ]
}

Thanks,
Manish

Thursday, November 26, 2015

PHP Login web service | PHP code for login | PHP Simple webservices

Updated December 2026: this tutorial was first published in November 2015. The original code used the old mysql_* functions (removed in PHP 7) and was open to SQL injection, so it has been rewritten for PHP 8 with a secure login. The original code has been removed because it was not safe to copy.

A login web service lets your Android app check a user's email and password against a MySQL database on your server. The app sends the login details as JSON, and the server answers with a small JSON result that tells the app whether the login worked.

How it works

  1. The app sends a POST request with a JSON body: {"email": "...", "password": "..."}
  2. The server looks up the user by email only, using a prepared statement.
  3. The server checks the password with password_verify() against the stored hash. The real password is never stored.
  4. The server returns status 1 if the login is OK, and status 0 with a message if not.

What was wrong with the old version

  • It no longer runs: mysql_* functions were removed in PHP 7.
  • SQL injection: the email and password were joined straight into the SQL text, so a specially written "password" could log in without knowing the real one.
  • Plain-text passwords: the database compared passwords as plain text. If the database leaks, every password leaks with it.
  • Root database user: the code connected as root, which gives the script far more rights than it needs.

Step 1: The user table

Store a password hash, not the password. 255 characters leaves room for future hash formats.

CREATE TABLE user (
  id            INT AUTO_INCREMENT PRIMARY KEY,
  email         VARCHAR(255) NOT NULL UNIQUE,
  password_hash VARCHAR(255) NOT NULL,
  created_at    TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Step 2: Database connection (config.php)

Keep the connection in one file, so login and register share it. PDO with ERRMODE_EXCEPTION makes database errors easy to catch.

<?php
// Database settings: change these to your own.
// Use a dedicated database user with limited rights, not root.
const DB_HOST = 'localhost';
const DB_NAME = 'mydb';
const DB_USER = 'app_user';
const DB_PASS = 'change-me';

function db(): PDO
{
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO(
            'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]
        );
    }
    return $pdo;
}

Step 3: Register a user (register.php)

The key line is password_hash(): it turns the password into a one-way hash before it is saved.

<?php
require __DIR__ . '/config.php';
header('Content-Type: application/json');

$data     = json_decode(file_get_contents('php://input'), true) ?? [];
$email    = trim($data['email'] ?? '');
$password = $data['password'] ?? '';

if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($password) < 8) {
    http_response_code(400);
    echo json_encode(['status' => 0, 'message' => 'Valid email and a password of 8+ characters required']);
    exit;
}

// Never store the password itself, only its hash
$hash = password_hash($password, PASSWORD_DEFAULT);

try {
    $stmt = db()->prepare('INSERT INTO user (email, password_hash) VALUES (?, ?)');
    $stmt->execute([$email, $hash]);
    echo json_encode(['status' => 1, 'message' => 'registered']);
} catch (PDOException $e) {
    http_response_code(409);
    echo json_encode(['status' => 0, 'message' => 'Email already registered']);
}

Step 4: The login service (login.php)

<?php
require __DIR__ . '/config.php';
header('Content-Type: application/json');

function respond(int $status, string $message, int $httpCode = 200): void
{
    http_response_code($httpCode);
    echo json_encode(['status' => $status, 'message' => $message]);
    exit;
}

// 1. Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(0, 'Use POST', 405);
}

// 2. Read the JSON body: {"email": "...", "password": "..."}
$data     = json_decode(file_get_contents('php://input'), true) ?? [];
$email    = trim($data['email'] ?? '');
$password = $data['password'] ?? '';

if ($email === '' || $password === '') {
    respond(0, 'Email and password are required', 400);
}

// 3. Find the user by email (prepared statement: no SQL injection)
try {
    $stmt = db()->prepare('SELECT id, password_hash FROM user WHERE email = ?');
    $stmt->execute([$email]);
    $user = $stmt->fetch();
} catch (PDOException $e) {
    error_log($e->getMessage());   // log the details, never show them
    respond(0, 'error', 500);
}

// 4. Check the password against the stored hash
if ($user && password_verify($password, $user['password_hash'])) {
    respond(1, 'done');
}

// Same message whether the email or the password is wrong
respond(0, 'Email or password does not match', 401);

The JSON answers keep the same status and message format as the 2015 version, so existing apps can read them. Failed logins now also return an HTTP error code (400, 401 or 500). Some Android HTTP clients treat those as errors, so read the response body in your error handler too.

Login OK:           {"status":1,"message":"done"}
Wrong email/pass:   {"status":0,"message":"Email or password does not match"}   (HTTP 401)
Missing fields:     {"status":0,"message":"Email and password are required"}    (HTTP 400)
Server problem:     {"status":0,"message":"error"}                              (HTTP 500)

Step 5: Test it

You can test without the app, from a terminal:

# Register a test user
curl -X POST https://your-server.com/register.php \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"secret123"}'

# Log in
curl -X POST https://your-server.com/login.php \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"secret123"}'

Already using the old version?

If your existing table stores plain-text passwords in a password column, back up the database, then run this script once to hash them:

<?php
// Run ONCE if your old table stored plain-text passwords in a "password" column.
require __DIR__ . '/config.php';

db()->exec('ALTER TABLE user ADD COLUMN password_hash VARCHAR(255) NULL');

$update = db()->prepare('UPDATE user SET password_hash = ? WHERE id = ?');
foreach (db()->query('SELECT id, password FROM user') as $row) {
    $update->execute([password_hash($row['password'], PASSWORD_DEFAULT), $row['id']]);
}

db()->exec('ALTER TABLE user DROP COLUMN password');
echo "Done: passwords are now hashed.\n";

Security checklist

  • Run the service over HTTPS only, so passwords are encrypted on the way.
  • Use a database user with only the rights this script needs, never root.
  • Give the same message for a wrong email and a wrong password, so attackers can't find out which emails are registered.
  • Limit login attempts (for example 5 per minute per IP) to slow down password guessing.

Written for PHP 8 and MySQL. PHP code tested with PHP 8.3, December 2026.

Sunday, October 18, 2015

Android Fragmnet Example code with full stack maintain | Fragment demo application | Simple Fragment example with action bar back button stack handle

Hello Friends,

Today I am going to share code for how to create android fragment and how to handle back stack. Have a look at below code or you can download full code from GIT server.



1)LoginActivity.java-

package com.androidhub4you.fragmentdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
public class LoginActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        findViewById(R.id.button__activity_main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent mIntent=new Intent(LoginActivity.this,MainActivity.class);
                startActivity(mIntent);
            }
        });
    }
}


2)activity_login.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:text="Login Activity"
        android:textSize="26sp"
        android:textStyle="bold"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_above="@+id/button__activity_main"
        android:layout_width="match_parent"
        android:text="(From Login Activity we will open Main Activity and inside Main Activity we will add Main Fragment in container)"
        android:textSize="18sp"
        android:textStyle="bold"
        android:gravity="center"
        android:layout_marginBottom="50dp"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button__activity_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="15dp"
        android:text="Open Main Activity"
        android:textSize="20sp"
        android:layout_centerInParent="true"
        android:paddingTop="15dp" />
</RelativeLayout>

  
 3)MainActivity.java-
package com.androidhub4you.fragmentdemo; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; /** * Manish Srivastava */ public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.v("<<main activity>>", "<<screen>>"); //display home back button ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); //In side Create method of MainActivity we will add main fragment FragmentTransaction transaction = getFragmentManager().beginTransaction(); FragmentMain fragmentMain = new FragmentMain(); transaction.addToBackStack("fragmentMain"); transaction.replace(R.id.container, fragmentMain); transaction.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: handleBackStack(); break; case R.id.action_settings: //do nothing break; } return super.onOptionsItemSelected(item); } //handle back stack from hardware back button and top action bar home back button public boolean handleBackStack() { //on back press check the count of fragment in stack int count = getFragmentManager().getBackStackEntryCount(); Log.v("<<Fragment in stack>>",String.valueOf(count)); if (count == 1) { //if count is 0 then finish main activity finish(); }else { //else remove one fragment from the stack FragmentTransaction transaction = getFragmentManager().beginTransaction(); getFragmentManager().popBackStackImmediate(); transaction.commit(); } return true; } //set action bar title name public void setActionBarTitle(String title) { getSupportActionBar().setTitle(title); } //handle the hardware back press @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK){ handleBackStack(); return true; } return super.onKeyDown(keyCode, event); } }
4)activity_main.xml-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</RelativeLayout>

5)FragmentMain.java-
package com.androidhub4you.fragmentdemo;

import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * Manish Srivastava
 */
public class FragmentMain extends Fragment {


    public FragmentMain() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        final Button mButtonFragmentMain=(Button)view.findViewById(R.id.button__fragment_main);

        Log.v("<< main fragment>>","<<screen>>");

        mButtonFragmentMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //call the child fragment
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                FragmentChild fragmentChild = new FragmentChild();
                transaction.addToBackStack("fragmentChild");
                transaction.replace(R.id.container, fragmentChild);
                transaction.commit();

            }
        });

        //call the main activity set tile method
        ((MainActivity)getActivity()).setActionBarTitle("Home Fragment");

        return view;
    }
}
6)fragment_main.xml-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Main Fragment Screen"
        android:textSize="26sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button__fragment_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:paddingBottom="15dp"
        android:paddingTop="15dp"
        android:text="Open Child Fragment"
        android:textSize="20sp" />
</RelativeLayout>
7)FragmentChild.java-
package com.androidhub4you.fragmentdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Manish Srivastava
 */
public class FragmentChild extends Fragment {


    public FragmentChild() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_child, container, false);

        //call the main activity set tile method
        ((MainActivity)getActivity()).setActionBarTitle("Child Fragment");


        return view;
    }
}

8)fragment_child.xml-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Child Fragment Screen"
        android:textSize="26sp"
        android:textStyle="bold" />
</RelativeLayout>

DOWNLOAD FULL CODE 
 
Thanks!
Manish