Wednesday, August 12, 2015

How to Determine Connectivity Status in Android — ConnectivityManager & NetworkCapabilities

While developing Android applications, a common use case is to schedule regular updates of application data from Internet resources, cache data, or execute long-running downloads. But if you aren't connected to the Internet, or the connection is too slow to complete your download, you should avoid waking the device or starting a network operation. So before you trigger any of these activities you need to check the connectivity status.

You can use the ConnectivityManager to check that you're actually connected to the Internet, and if so, what type of connection is in place (Wi‑Fi, cellular, ethernet, etc.). The Android docs are here: https://developer.android.com/reference/android/net/ConnectivityManager

Permissions

Make sure the following permission is declared in AndroidManifest.xml so your app can query connectivity state:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Legacy example (NetworkInfo)

The following snippet shows how to use ConnectivityManager to query the active network and determine if it has connectivity. This is the original/legacy approach and uses NetworkInfo (deprecated in API 29):

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

You can also check the type of the active network to determine whether it is Wi‑Fi:

boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

Notes about the legacy approach:

  • NetworkInfo and isConnectedOrConnecting were commonly used in older Android versions, but NetworkInfo is deprecated starting in API level 29. Prefer the modern NetworkCapabilities approach on newer devices.

Modern approach (API 29+): NetworkCapabilities

On Android Q (API 29) and later, use NetworkCapabilities and getActiveNetwork() to inspect the currently active network in a more accurate way. NetworkCapabilities lets you check both transport type and capabilities such as NETCAPABILITYINTERNET and NETCAPABILITYVALIDATED.

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = cm.getActiveNetwork(); // may be null
NetworkCapabilities nc = cm.getNetworkCapabilities(network);

boolean hasInternet = nc != null && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
boolean validated = nc != null && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
boolean isWifi = nc != null && nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);

Explanation:

  • NETCAPABILITYINTERNET means the network can reach the Internet in principle.
  • NETCAPABILITYVALIDATED indicates the platform has validated that the network can actually reach the Internet (often more useful to decide whether to attempt network IO).
  • Use hasTransport(…) to detect TRANSPORTWIFI, TRANSPORTCELLULAR, TRANSPORTETHERNET, TRANSPORTVPN, etc.

Listening for changes: registerNetworkCallback

If you need to be notified of connectivity changes (rather than polling), register a NetworkCallback:

NetworkRequest request = new NetworkRequest.Builder()
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        .build();

ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // network became available
    }

    @Override
    public void onLost(Network network) {
        // network lost
    }
};

cm.registerNetworkCallback(request, callback);
// Remember to unregister when appropriate: cm.unregisterNetworkCallback(callback);

Testing and troubleshooting

  • In the emulator you can simulate network conditions or disable the network.
  • Use adb to toggle airplane mode or modify network rules if needed.
  • Prefer checking NETCAPABILITYVALIDATED when you need a reliable indication that the network can reach the public Internet.

Summary

  • The original ConnectivityManager + NetworkInfo approach works on older devices but is deprecated (API 29+).
  • Use NetworkCapabilities.getNetworkCapabilities(getActiveNetwork()) and check capabilities and transports on modern Android.
  • Always declare ACCESSNETWORKSTATE in the manifest.

It's also possible to determine the type of Internet connection currently available. Device connectivity can be provided by mobile data, WiMAX, Wi‑Fi, and ethernet connections. By querying the type of the active network you can adjust behavior (for example, refresh rate or large downloads) based on bandwidth.

If "isWiFi" is true then the device is using Wi‑Fi connection. That's it. Happy coding.

References:

Wednesday, June 24, 2015

Convert date strings to MySQL DATE in PHP — strtotime() and DateTime examples

I was working on a Web portal, where there was a use case to import the csv or xls to a MySql database. In the database there was a field for date with the date data type. And from the xls or csv when we are importing, it imports as the string. So when you are trying to insert a string or text in date data type, it adds as 0000-00-00 which is wrong.

For that, to insert it correctly we need to convert the date string to date format before inserting.

Consider the below csv file to be imported. Dob (Date of Birth) is the column that contains the date.

CSV date example image

First row is the header. Now the content of the DOB, DOJ and Anniversary columns has to be converted to date format. Below is the code to be considered to convert it.

Quick solution (original approach)

//For DOB

$time = strtotime($data[7]);
$data[7] = date('Y-m-d', $time);

// For DOJ

$time = strtotime($data[8]);
$data[8] = date('Y-m-d', $time);

//For Anniversary

$time = strtotime($data[11]);
$data[11] = date('Y-m-d', $time);

strtotime(string) is the function that converts the string to time format. Now this has to be converted to required date format. That can be done using date(format, time) function.

Format you can use the required format. Here I am using yyyy-mm-dd format for that we can use Y-m-d. Now the $data[7], $data[8] and $data[11] contains the date in date datatype and also in yyyy-mm-dd format.

That's it. Happy Coding


Explanation and important checks

  • strtotime() returns FALSE on failure. If you pass that FALSE to date('Y-m-d', $time), PHP converts it to 1970-01-01 or you may end up inserting an incorrect value — your original symptom of 0000-00-00 usually happens when MySQL receives an invalid date string.
  • Always check the return value before formatting.

Example with checks:

// Example check before formatting
$time = strtotime($data[7]);
if ($time === false || empty($data[7])) {
    // handle invalid or empty input: set to NULL or skip
    $data[7] = null; // or use a default
} else {
    $data[7] = date('Y-m-d', $time);
}

Safer approach: DateTime and createFromFormat()

strtotime() works for many common formats, but if your CSV uses a specific format (for example dd/mm/yyyy or mm-dd-yyyy), prefer DateTime::createFromFormat() so you can parse deterministically.

Example parsing a dd/mm/yyyy input and handling failure:

$dateString = trim($data[7]); // e.g. "31/12/1980"
if ($dateString === '') {
    $data[7] = null; // treat empty as NULL in DB
} else {
    $dt = DateTime::createFromFormat('d/m/Y', $dateString);
    $errors = DateTime::getLastErrors();
    if ($dt === false || $errors['warning_count'] > 0 || $errors['error_count'] > 0) {
        // parsing failed — fallback or log
        // try a fallback with strtotime:
        $time = strtotime($dateString);
        if ($time !== false) {
            $data[7] = date('Y-m-d', $time);
        } else {
            $data[7] = null; // or flag this row for manual review
        }
    } else {
        // convert to MySQL DATE format
        $data[7] = $dt->format('Y-m-d');
    }
}

This approach avoids ambiguous parsing and is more robust when you know the input format.

Inserting into MySQL safely (use prepared statements)

Don't concatenate date strings into SQL. Use parameterized queries. Example using PDO inserting a DATE (or NULL):

// assume $pdo is a configured PDO instance
$sql = "INSERT INTO people (name, dob, doj, anniversary) VALUES (:name, :dob, :doj, :anniv)";
$stmt = $pdo->prepare($sql);

// $data[7], $data[8], $data[11] now contain either 'Y-m-d' strings or null
$stmt->execute([
    ':name' => $data[0],
    ':dob' => $data[7],      // PDO will convert null to SQL NULL
    ':doj' => $data[8],
    ':anniv' => $data[11]
]);

If you must use mysqli, use prepared statements similarly.

Handling multiple input formats

  • If the CSV may contain multiple date formats, implement a normalization function:
  • Try DateTime::createFromFormat for a list of expected formats.
  • Fallback to strtotime().
  • If still failing, log the row and keep it for manual review.

Example helper:

function normalizeDateToYmd($input, array $formats = ['d/m/Y', 'm/d/Y', 'Y-m-d']) {
    $s = trim($input);
    if ($s === '') return null;
    foreach ($formats as $fmt) {
        $dt = DateTime::createFromFormat($fmt, $s);
        $errors = DateTime::getLastErrors();
        if ($dt !== false && $errors['warning_count'] === 0 && $errors['error_count'] === 0) {
            return $dt->format('Y-m-d');
        }
    }
    // fallback to strtotime
    $t = strtotime($s);
    if ($t !== false) return date('Y-m-d', $t);
    return null; // unable to parse
}

Edge cases and tips

  • Empty or invalid date fields: insert SQL NULL instead of '0000-00-00'.
  • Timezones: DATE in MySQL has no timezone, but if your CSV has times or timezone offsets, normalize before truncating.
  • Excel dates: XLS/XLSX may export dates as Excel serial numbers. Use a library (e.g., PhpSpreadsheet) and convert Excel date serials to PHP dates.
  • Logging: collect rows with unparseable dates and report them rather than silently inserting NULL.
  • Input sanitation: always trim input and remove non-printable characters before parsing.

References

That's it. Happy Coding

Thursday, June 11, 2015

Essential Eclipse IDE Keyboard Shortcuts — Windows & Linux (Cheat Sheet)

Editors are an integral part of programming. There are a lot of editors available; Eclipse has been a widely used Java IDE. Shortcuts make life much easier when you are working with any IDE. Below is a collected cheat sheet of the most useful Eclipse keyboard shortcuts for Windows and Linux. (Mac OS typically uses the Cmd key instead of Ctrl.)

Note: This page lists the shortcuts as the author wrote them. If you rely on a specific Eclipse release, verify shortcuts in your Eclipse key preferences.

Table of contents

Notes

  • Shortcuts below are given for Windows and Linux. On macOS, replace Ctrl with Cmd where applicable.
  • The list is presented in the same grouping the author used so you can jump to categories quickly.

1. Manage Files and Projects

  • Ctrl+N : Create new project using the Wizard
  • Ctrl+Alt+N : Create new project, file, class, etc.
  • Alt+f, then . : Open project, file, etc.
  • Ctrl+Shift+R : Open Resource (file, folder or project)
  • Alt+Enter : Show and access file properties
  • Ctrl+S : Save current file
  • Ctrl+Shift+S : Save all files
  • Ctrl+W : Close current file
  • Ctrl+Shift+W : Close all files
  • Ctrl+P : Print the file
  • F5 : Refresh content of selected element with local file system

2. Editor Window

Focus/cursor must be in the editor window for these to work.

  • F12 : Jump to Editor Window
  • Ctrl+PageDown / Ctrl+PageUp : Switch to next editor / previous editor
  • Ctrl+M : Maximize or minimize current editor window (also works for other windows)
  • Ctrl+E : Show list of open editors (use arrow keys and Enter to switch)
  • Ctrl+F6 / Ctrl+Shift+F6 : Show list of open editors; switches immediately upon release of Ctrl
  • Alt+← / Alt+→ : Go to previous / next editor window
  • Alt+- : Open editor window option menu
  • Ctrl+F10 : Show view menu (features available on left vertical bar: breakpoints, bookmarks, line numbers, …)
  • Ctrl+F10, then n : Show or hide line numbers
  • Ctrl+Shift+Q : Show or hide the diff column on the left (changes since last save)

3. Navigate in Editor

  • Home / End : Jump to beginning / end of indentation. Press Home twice to jump to beginning of line
  • Ctrl+Home / Ctrl+End : Jump to beginning / end of source
  • Ctrl+← / Ctrl+→ : Jump one word left / one word right
  • Ctrl+Shift+↓ / Ctrl+Shift+↑ : Jump to previous / next method
  • Ctrl+L : Jump to line number. (To hide/show line numbers: Ctrl+F10 then select 'Show Line Numbers')
  • Ctrl+Q : Jump to last location edited
  • Ctrl+. / Ctrl+, : Jump to next / previous compiler syntax warning or error
  • Ctrl+Shift+P : With a bracket selected: jump to the matching bracket
  • Ctrl+[+] / Ctrl+- on numeric keypad : Collapse / expand current method or class
  • Ctrl+[/] / Ctrl+* on numeric keypad : Collapse / expand all methods or classes
  • Ctrl+↓ / Ctrl+↑ : Scroll editor without changing cursor position
  • Alt+PageUp / Alt+PageDown : Next sub-tab / previous sub-tab
  • Ctrl+F7 : Next View
  • Ctrl+Shift+F7 : Previous View
  • Ctrl+F8 : Next Perspective
  • Ctrl+Shift+F8 : Previous Perspective
  • Ctrl+. : Go to the next problem / error
  • Ctrl+, : Go to the previous problem / error

4. Select Text

  • Shift+→ / Shift+← : Expand selection by one character right / left
  • Ctrl+Shift+→ / Ctrl+Shift+← : Expand selection to next / previous word
  • Shift+↓ / Shift+↑ : Expand selection by one line down / up
  • Shift+End / Shift+Home : Expand selection to end / beginning of line
  • Ctrl+A : Select all
  • Alt+Shift+↑ : Expand selection to current element (e.g., current one-line expression or content within brackets)
  • Alt+Shift+← / Alt+Shift+→ : Expand selection to next / previous element
  • Alt+Shift+↓ : Reduce previously expanded selection by one step

5. Edit Text

  • Ctrl+C / Ctrl+X / Ctrl+V : Copy, Cut and Paste
  • Ctrl+Z : Undo last action
  • Ctrl+Y : Redo last (undone) action
  • Ctrl+D : Delete line
  • Alt+↑ / Alt+↓ : Move current line or selection up or down
  • Ctrl+Alt+↑ / Ctrl+Alt+↓ : Duplicate current line or selection up or down (note: on some Windows setups these shortcuts may rotate the screen)
  • Ctrl+Delete : Delete next word
  • Ctrl+Backspace : Delete previous word
  • Shift+Enter : Enter line below current line
  • Shift+Ctrl+Enter : Enter line above current line
  • Insert : Toggle between insert and overwrite mode
  • Shift+Ctrl+Y : Change selection to all lower case
  • Shift+Ctrl+X : Change selection to all upper case

6. Search and Replace

  • Ctrl+F : Open find and replace dialog
  • Ctrl+K / Ctrl+Shift+K : Find previous / find next occurrence of search term (close find window first)
  • Ctrl+H : Search workspace (Java Search, Task Search, and File Search)
  • Ctrl+J / Ctrl+Shift+J : Incremental search forward / backwards (type search term after pressing Ctrl+J)
  • Ctrl+Shift+O : Open a resource search dialog to find any class
  • Ctrl+J : Incremental search without popup dialog; press Ctrl+J to find the next match
  • Ctrl+Shift+G : In the Java editor, search for references in the workspace
  • Ctrl+Shift+P : Select the matching bracket (cursor needs to be before or after a bracket)

7. Indentations and Comments

  • Tab / Shift+Tab : Increase / decrease indent of selected text
  • Ctrl+I : Correct indentation of selected text or current line
  • Ctrl+Shift+F : Autoformat all code in editor using code formatter
  • Ctrl+/ : Comment / uncomment line or selection (adds //)
  • Ctrl+Shift+/ : Add block comment around selection (adds /* ... */)
  • Ctrl+Shift+\ : Remove block comment
  • Alt+Shift+J : Add element comment (adds /** ... */)

8. Editing Source Code

  • Ctrl+Space : Opens Content Assist (show available methods, fields, etc.)
  • Ctrl+1 : Open Quick Fix and Quick Assist
  • Alt+/ : Propose word completion (after typing at least one letter; press repeatedly to cycle options)
  • Ctrl+Shift+Insert : Deactivate or activate Smart Insert Mode (automatic indentation, automatic brackets, etc.)

9. Code Information

  • Ctrl+O : Show code outline / structure
  • F2 : Open class, method, or variable information (tooltip text)
  • F3 : Open Declaration — jump to declaration of selected class, method, or parameter
  • F4 : Open Type Hierarchy window for selected item
  • Ctrl+T : Show / open Quick Type Hierarchy for selected item
  • Ctrl+Shift+T : Open Type in Hierarchy
  • Ctrl+Alt+H : Open Call Hierarchy
  • Ctrl+U : Find occurrences of expression in current file
  • Ctrl+move over method : Open Declaration or Implementation (hover and Ctrl+click behavior)

10. Refactoring

  • Alt+Shift+R : Rename selected element and all references
  • Alt+Shift+V : Move selected element to other class or file (with complete method or class selected)
  • Ctrl+Shift+C : Change method signature (with method name selected)
  • Alt+Shift+M : Extract selection to method
  • Alt+Shift+L : Extract local variable (create and assign a variable from a selected expression)
  • Alt+Shift+I : Inline selected local variables, methods, or constants if possible

11. Run and Debug

  • Ctrl+F11 : Save and launch application (Run)
  • F11 : Debug
  • F5 : Step Into function
  • F6 : Next step (line by line)
  • F7 : Step out
  • F8 : Resume / Skip to next Breakpoint

12. Others

  • Ctrl+F7 / Ctrl+Shift+F7 : Switch forward / backward between views (panels)
  • Ctrl+F8 / Ctrl+Shift+F8 : Switch forward / backward between perspectives
  • Ctrl+P : Print
  • F1 : Open Eclipse Help
  • Shift+F10 : Show context menu (right click)
  • Ctrl+3 : Quick Access — focus the Quick Access box to execute any Eclipse command
  • Ctrl+Shift+O : Organize imports
  • Alt+Shift+S then R : Generate getter and setter methods
  • Ctrl+Space : Type assist (Content Assist)
  • Alt+Shift+Z : Enclose block in try-catch
  • Shift+F2 : Show Javadoc for current element

Last updated: (replace with actual date when you update this page)

If you want this as a printable one-page cheat sheet, consider generating a PDF from this page or linking to a downloadable image. If you customize or rebind keys in Eclipse, set a note or link to your key-bindings guide under the editor preferences.

Saturday, May 30, 2015

How to reference XML views in an Android Fragment (findViewById examples)

While developing an Android application using an Activity, we typically reference XML elements with findViewById like this:

TextView name = (TextView) findViewById(R.id.Config_name);

This works when your class extends Activity, because Activity provides findViewById. When your class extends Fragment, calling findViewById directly on the Fragment will not compile — the method isn't available on Fragment.

How to reference views from a Fragment

You can still use findViewById from a Fragment, but you must call it on the fragment's root view (after the layout has been inflated). There are two common ways to do this:

1) Use getView() (after the view is created):

TextView name = (TextView) getView().findViewById(R.id.Config_name);

Note: getView() returns the Fragment's root view and is only non-null after the view has been created (for example, after onCreateView returns and typically in or after onViewCreated). Calling getView() too early can return null.

2) Use the view returned by inflater when you inflate the layout in onCreateView:

View myFragmentView = inflater.inflate(R.layout.MyLayout, container, false);
TextView name = (TextView) myFragmentView.findViewById(R.id.Config_name);

This approach is explicit and safe because you are using the view object you just inflated.

Minimal onCreateView example

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.MyLayout, container, false);
    TextView name = (TextView) root.findViewById(R.id.Config_name);
    // initialize other views here
    return root;
}

Or, using onViewCreated (the view is already created and attached):

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    TextView name = (TextView) view.findViewById(R.id.Config_name);
}

Notes and tips

  • Always make sure you access views after the layout is inflated (onCreateView/onViewCreated) to avoid NullPointerExceptions.
  • The examples above are Java; in Kotlin you can use view.findViewById(R.id.Config_name) or prefer View Binding for safer, null-safe access.
  • Modern Android projects commonly use View Binding or Kotlin view binding delegates instead of manual findViewById — consider adding a View Binding example if you update this post later.

That's it. Use these patterns for TextView or any other view in your fragment. Hope this helps. Happy Coding.

Friday, May 29, 2015

How to Convert an Android Activity to a Fragment — Step-by-Step

Earlier I developed an android application using the Activity. But now the trend is to develop the android application using the Fragments. So I thought of converting the Activity based android application to Fragment based Android application. Earlier I thought it’s very difficult to do it. But It’s very simple.

Overview

Here are the steps how we convert an activity to a Fragment:

Prerequisite

  • Basic knowledge of Android Activities and Fragments.
  • If you are using the Support Library, the article uses android.support.v4.app.Fragment types as shown below. Newer projects may use the AndroidX equivalents (androidx.fragment.app.Fragment).

Steps

  1. First we need to import the package: FragmentActivity of Support V4 app package:
Import android.support.v4.app.FragmentActivity;
  1. Change the extends Activity to extends Fragment. Eg:
public class HomeFragment extends Fragment{

}
  1. Add the method onCreateView and move everything from onCreate of Activity to onCreateView except super.onCreate() and setContentView()
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View v = null;
    v = inflater.inflate(R.layout.fragment_home, parent, false);

    // Content of previous onCreate() here
    // ...

    // Don't use this method, it's handled by inflater.inflate() above :
    // setContentView(R.layout.fragment_home);

    return v;
}
  1. Remove method onCreate().

  2. Everywhere you access the Activity with "this" or just something or "this.something" replace with super.getActivity(). or use the value saved in the onCreateView

Example:

// Before (in Activity)
Intent i = getIntent();

// In Fragment
Intent i = super.getActivity().getIntent();

That’s it. Happy Coding…