Thursday, May 12, 2016

Add a Splash Screen in Android Studio — 3‑Second Example (Updated Best Practices)

Most of the Android apps use a splash screen before launching their main activity; you can see this with popular apps such as Skype, Facebook, Dropbox, etc.

While I was developing an Android APP POC for one of my customer, the requirement was to create a splash screen with their logo which stays on the screen for 3 seconds. Below are clear steps and code examples you can follow.

Prerequisites

  • Android Studio (recommended recent stable version)
  • A new or existing Android project
  • A splash image (eg. splash_image.jpg) to place in your project's drawable folders

Overview

Two common approaches:

  1. Theme-based launch screen (recommended for fastest cold start)
  2. Separate Splash Activity (simple to implement — retains the author’s original approach)

This article preserves the original example and also shows a modern, safer implementation.

1) Create a new project in Android Studio

  1. File -> New Project
  2. Enter Application Name and Minimum SDK, Click Next
  3. Select Blank Activity, Click Next
  4. Click Finish

This creates the Android application with a blank activity. Next we will add the splash screen.

2) Create the splash layout

Create a layout file named res/layout/splash.xml with a simple LinearLayout that uses a drawable as the background. (The original article used a background drawable named splash_image.)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splash_image">
</LinearLayout>

Place your splash image file (for example splash_image.jpg) into your app/src/main/res/drawable or into density-specific folders like drawable-hdpi, drawable-xhdpi depending on your asset. For images that should not be scaled by Android, use drawable-nodpi.

3) Original (author's) Splash Activity example

The original sample shows a Splash Activity that waits for 3 seconds and then launches MainActivity. The unmodified original code (kept for reference) is shown below.

// SplashScreen.java
package marutsoft.vehicledata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import android.widget.ImageView;

/**
 * Created by Karjol G T on 11-05-2016.
 */
public class SplashScreen extends Activity {

    protected int _splashTime = 3000;
    private Thread splashThread;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Display display = getWindowManager().getDefaultDisplay();
        setContentView(R.layout.splash);

        Thread timerThread = new Thread(){
            public void run(){
                try{
                    sleep(3000);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }finally{
                    Intent intent = new Intent(SplashScreen.this,MainActivity.class);
                    startActivity(intent);
                }
            }
        };
        timerThread.start();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        finish();
    }
}

Notes on the original approach:

  • This uses a background thread and sleep(3000). While it works in many cases, it is not the recommended pattern for modern Android apps. If misused it can block the UI or cause unexpected lifecycle behavior.
  • onPause() calls finish() to ensure the splash activity is removed from the back stack.

4) Manifest entry (make the splash activity the launcher)

Add the splash activity to your AndroidManifest.xml and make it the LAUNCHER activity. (Keep your package name.) The original manifest snippet:

<activity
    android:name=".SplashScreen"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>

5) Recommended modern implementation (non-blocking)

A safer and simpler approach is to use a Handler.postDelayed(...) from the UI thread (or new Handler(Looper.getMainLooper()) on newer platforms). Also prefer AppCompatActivity (or AndroidX ComponentActivity / AppCompatActivity) and call finish() after starting the main activity so the user does not return to the splash.

// SplashScreen.java (recommended modern approach)
package marutsoft.vehicledata;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity; // or import android.support.v7.app.AppCompatActivity for older projects

public class SplashScreen extends AppCompatActivity {

    private static final long SPLASH_DELAY_MS = 3000L; // 3 seconds

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

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(intent);
                finish(); // remove SplashScreen from back stack
            }
        }, SPLASH_DELAY_MS);
    }
}

Why this is better:

  • No manual Thread management or sleeping; uses Android's message queue and is safe on modern devices.
  • Cleaner lifecycle handling when you call finish() after starting the main activity.
  • Uses AppCompat so it's straightforward to compile in modern Android Studio projects.

6) Alternative best-practice: theme-based launch screen

For fastest cold start it is recommended to use a theme-based splash implemented with windowBackground in your app theme. This avoids inflating a layout or starting an activity before the first frame is shown. In short:

  • Create a drawable (or layer-list) for the splash look
  • Set it as windowBackground in a launch theme
  • Use that theme for your LAUNCHER activity in the manifest

This method provides the fastest perceived startup time and is the recommended pattern for production apps. See the linked resources at the end for a dedicated guide.

7) Additional notes and troubleshooting

  • Rotation: if your splash activity must survive rotation, avoid re-posting delayed callbacks multiple times. You can lock orientation or keep the activity lightweight.
  • Long startup work: do not perform heavy initialisation on the UI thread during splash. Offload to background threads and show progress only if necessary.
  • Assets: put different density images in drawable-*/ folders or use drawable-nodpi if you do not want Android to scale the image.
  • Accessibility: when displaying logos in a view, provide content descriptions for screen readers. In a background-only layout, ensure the important content is accessible elsewhere in the app.

8) Run the app

Run the Android application to check the splash screen running at the beginning of the application.

That's it. Happy Coding..


Created by Karjol G T (original example preserved).

Saturday, May 7, 2016

Sorting Multidimensional Arrays in PHP — array_multisort and usort Examples

I was working on a project. I had to do a lot of interaction between a MySQL server and my Android app. In that case I got a situation where I get the raw data from the database which I needed to sort and show on the fly. This data is in a multi-dimensional array.

Problem

I used to get the items data from MySQL based on the user id, build a products array, and then sort it by the bay value so the app can consume ordered results.

Original code (as used in the project)

The original code used mysql_* functions and built the array like this:

$result = mysql_query("SELECT * FROM savedlist where uid='$uid' ") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
    $response['products'] = array();
    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $itemtypes = array();
        $itemtypes['id']=$row['pid'];

        $result1 = mysql_query("SELECT * FROM items where id='$row[pid]'") or die(mysql_error());

        while ($row1 = mysql_fetch_array($result1)) {
            $itemtypes['name'] = $row1['name'];
            $itemtypes['price']=$row1['price'];
            $itemtypes['bay']=$row1['bay'];
        }

        print_r($itemtypes, true);
        // push single product into final response array
        array_push($response['products'], $itemtypes);

        $bays = array();
        foreach ($response['products'] as $bay)
        {
            $bays[] = $bay['bay'];
        }

        array_multisort($bays,SORT_ASC, $response['products'] );
    }
}

Here $response['products'] is a multi-dimensional array which the author wanted to sort based on the BAY. So first a separate $bays[] array is created from each product's 'bay' value and then array_multisort() is used.

Note: The article later shows an alternate call: array_multisort($response['products'], SORT_ASC, $bays); — this is the wrong order for what the author intended. The correct form is shown below.

Correct usage of array_multisort for this case

array_multisort sorts arrays in parallel: you pass the array of sort keys first, then the order and finally the array(s) you want reordered to match. For the example above the correct call is:

array_multisort($bays, SORT_ASC, $response['products']);

This ensures $bays is used as the sort key and $response['products'] is re-ordered to match that sorted key array.

Why order matters

array_multisort uses the first array you pass as the primary sort key. If you pass the data array first it will try to sort that array directly (which is not what you intended) and the $bays array will be treated as a secondary array.

A simpler and often clearer alternative: usort

For sorting a single key inside an array of associative arrays, usort with a comparison function is usually easier and more readable:

usort($response['products'], function($a, $b) {
    // PHP 7+ spaceship operator:
    return $a['bay'] <=> $b['bay'];
});

// or, if you prefer ascending numeric comparison without spaceship:
usort($response['products'], function($a, $b) {
    if ($a['bay'] == $b['bay']) return 0;
    return ($a['bay'] < $b['bay']) ? -1 : 1;
});

usort modifies $response['products'] in place and is often the most straightforward choice when you only need to sort by one field.

Example: build then sort (complete flow)

Here's a clearer flow that keeps the original structure but shows the sorting step separately. (This still uses the original mysql_* calls — see the modernization note below.)

$response['products'] = array();

// -- build the products array (as original) --
// ... (database fetch loops from original code) ...
// after pushing all $itemtypes into $response['products']

// build the key array
$bays = array();
foreach ($response['products'] as $product) {
    $bays[] = $product['bay'];
}

// sort by bay ascending and reorder products to match
array_multisort($bays, SORT_ASC, $response['products']);

// or, using usort (recommended for single-key sorts):
usort($response['products'], function($a, $b) {
    return $a['bay'] <=> $b['bay'];
});

// final output example (JSON for mobile app):
echo json_encode($response, JSON_PRETTY_PRINT);

Important modernization and security notes

  • The mysql_* extension used in the original code has been removed from PHP as of PHP 7 and is deprecated. For new code use mysqli (procedural or object oriented) or PDO with prepared statements to avoid SQL injection and to be compatible with current PHP versions.
  • Avoid using die(mysql_error()) in production. Handle errors gracefully and do not reveal internal database errors to end users.
  • If you are building an API consumed by an Android app, ensure you return properly encoded JSON and set appropriate response headers.

When to use array_multisort vs usort

  • Use array_multisort when you need to sort by multiple columns with different sort directions (it can sort multiple arrays in tandem).
  • Use usort when you sort by a single key (or when you prefer a comparison function); usort tends to be clearer for single-key sorts and easier to read/maintain.

References

That's it. Happy Coding

Thursday, May 5, 2016

Download Durmukhi Naam Samvastara (SRSM Panchanga) — English Version Available

Greeting of the Day!!!

First of all I am very sorry for delaying in updation of Durmukhi Naam Samvastara data. And thanks to all those who written to me to update it. Now it's updated and the app is ready to download with all the data for Durmukhi Naam Samvastara.

Download

The updated SRSM Panchanga app (Durmukhi Naam Samvastara) is available to download from the Google Play Store:

https://play.google.com/store/apps/details?id=com.sarga.simplecal

Please uninstall the older version of the application if installed and install this new version.

App details (update these from Play Store when editing)

  • App name: SRSM Panchanga (Durmukhi Naam Samvastara)
  • Language: English (Kannada version coming soon)
  • Where to download: Google Play Store (link above)

Note: When updating the live post, include exact Play Store metadata such as version number, APK size, required Android version, and release date. Do not add those here unless taken directly from the Play Store listing.

How to install

  1. Open the Play Store link above on your Android device or visit the page from a desktop browser.
  2. If you have an older version installed, uninstall it first:
  • Settings → Apps → SRSM Panchanga → Uninstall
  1. Tap "Install" on the Play Store page.
  2. Once installed, open the app and verify the data is updated.

Notes

  • The app is currently available in English. Kannada version will be available soon.
  • Thank you to everyone who wrote in requesting the update — your feedback helped prioritize this release.

Contact / Feedback

If you face issues or want to report problems with the data, please reply to this post or use the blog's contact mechanism to let me know.

Sunday, April 3, 2016

Embed Facebook Page Timeline on Your Website — Page Plugin Guide

Greetings Of the day!!!

Quick summary

I was working on a website and wanted to include updates from my Facebook Page on the site. I found a simple solution in Facebook's developer console. Below is the exact process I used to include Facebook Page updates on a website.

What you'll need

  • The public URL of your Facebook Page
  • Access to edit your website's HTML (so you can paste the code)
  • A moment to configure the Page Plugin at Facebook Developers

Step-by-step

  1. Go to the Page Plugin page on Facebook Developers:

https://developers.facebook.com/docs/plugins/page-plugin/

  1. Enter the details about the Facebook Page (your Page URL and the display options you want).

  2. After entering all the details, press the "Get Code" button.

Facebook Page Plugin configuration screenshot

  1. Copy the code that pops up after pressing the Get Code button.

Get Code popup screenshot

  1. You can paste this code in the HTML file of your website. After pasting, you should be able to see the Facebook Page with Like and Share buttons and all the status updates on the page.

Code copy screenshot

Example

You can visit the site I used for this example: http://drvbhosagoudar-bioresearch.org/ — you should see the Facebook Page plugin on the left side of that site.

Notes and tips

  • The Facebook Page Plugin generates code for you. Paste exactly what Facebook returns in the "Get Code" popup into your HTML where appropriate. Typically, Facebook provides a small JavaScript SDK snippet and an iframe option — follow the instructions in the popup.
  • If you are using a CMS (Blogger, WordPress, etc.), paste the provided markup into an HTML/Custom HTML widget or into the template where you want the plugin to appear.
  • If the Facebook developer console UI looks different, check Facebook's Page Plugin documentation (link above) — the UI and options occasionally change.

That's it. Happy coding.

Friday, April 1, 2016

How to import an .sql file into MySQL from the command line

When I was working with the MySql command prompt, I was wondering how to import an available sql file into the available database.

Overview

This short guide shows two simple ways to import an .sql file into an existing MySQL database from the command line:

  • Using the mysql client interactive prompt with the SOURCE command
  • From the operating-system shell using input redirection (<)

Prerequisites

  • MySQL client (mysql) installed and on your PATH
  • Database already created (you will import into an existing database)
  • Credentials (username and password) with permissions to create/modify tables in the target database
  • Path to the .sql file you want to import (absolute or relative)

Method 1 — inside the mysql client using SOURCE

  1. Open the MySQL command prompt and select the target database. In the example below the database is named smartcart:
mysql> use smartcart;
Database changed
  1. Use the SOURCE command with the path to your .sql file. The example uses f:/items.sql:
mysql> source f:/items.sql;
Query OK, 0 rows affected (0.07 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.76 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)
  1. Verify that the new table(s) from the SQL file were added to the database:
mysql> show tables;
+---------------------+
| Tables_in_smartcart |
+---------------------+
| items               |
| users               |
+---------------------+
2 rows in set (0.00 sec)

mysql> select * from items;
Empty set (0.06 sec)

Notes for Method 1:

  • The path you pass to SOURCE can be absolute or relative to the server/your client working directory. On Windows you can use drive letters (e.g. f:/items.sql) or surround paths with quotes if they contain spaces.
  • SOURCE runs all SQL statements in the file as if you typed them into the client.

Method 2 — from the OS shell using input redirection

You can import an SQL file directly from your command shell without first entering the mysql prompt. This is often faster for large files.

Example:

# From a Unix/Linux/macOS or Windows PowerShell/CMD shell
mysql -u username -p smartcart < f:/items.sql
# You will be prompted for the MySQL password

Notes for Method 2:

  • Replace username with your MySQL user and smartcart with the target database name.
  • If you omit the database name you can still import statements that include CREATE DATABASE / USE statements.
  • On Windows, ensure the path syntax is correct (you can also use double backslashes or forward slashes).

Troubleshooting and tips

  • Permissions: make sure the user you connect with has the required permissions on the target database.
  • File path: if you see "file not found" errors, verify the path and quoting. Try an absolute path.
  • Empty table after import: the file may only contain schema (CREATE TABLE) statements or no INSERT statements. Open the .sql file to confirm it contains INSERTs if you expect data.
  • Errors during import: the mysql client will print errors as it executes statements. Rerun the import after fixing the SQL or adjust the error-handling behavior (for automation, consider mysql --force to continue past errors).
  • Character set issues: if you see strange characters, specify --default-character-set=utf8mb4 (or appropriate charset) when invoking mysql.

Summary

Both SOURCE (inside the mysql client) and shell redirection (mysql < file.sql) are valid ways to import an .sql file. Use the method that fits your workflow: interactive debugging inside mysql or direct shell import for automation/large files.

That's it. Happy coding.