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…

Wednesday, May 20, 2015

How to integrate WhatsApp with an Android app or website — prefill messages using whatsapp://

We can integrate WhatsApp with an Android app in two ways:

Methods

  1. Using the Android Intent system (covered in my previous post: http://karjol-gt.blogspot.in/2015/05/how-to-share-media-or-message-text-with.html).
  2. Using the custom URL scheme provided by WhatsApp.

We will discuss the second option in this post.

WhatsApp custom URL scheme (website or app)

WhatsApp provides a custom URL scheme to interact with the app. If you have a website and want to open a WhatsApp chat with a pre-defined message, you can use WhatsApp’s custom URL scheme.

Opening whatsapp://send?text= followed by the text to send will open WhatsApp, allow the user to choose a contact, and prefill the input field with the specified text.

Example (on a website)

Use a normal anchor tag. The message must be URL-encoded (spaces become %20, etc.). Example:

<a href="whatsapp://send?text=Hello%20World!">Hello, world!</a>

When the user clicks this link, WhatsApp (if installed) opens, the user selects a contact, and the predefined text "Hello World!" appears in the chat input.

Notes and compatibility

  • URL-encode the message text. Unencoded spaces and special characters may break the URL.
  • This method relies on the whatsapp:// custom scheme and therefore requires the WhatsApp app to be installed on the device. Behavior can vary by platform, browser, and WhatsApp version. Test on the target devices and browsers.
  • Consider adding a fallback for environments where the whatsapp:// scheme is unsupported (for example, conditionally offering the WhatsApp FAQ or guiding users to install WhatsApp).

Summary

That’s it. Happy Coding…

Reference

Tuesday, May 19, 2015

Share Text and Media with Social Apps in Android — Intent examples and best practices

I was developing an android application for a customer. One requirement was to share some media and text with the installed social Android apps like Google+, Email, Gmail, Facebook, Drive, Messaging, WhatsApp etc. This post shows how to share predefined text and media from your app.

Overview

In Android you can share text or media with other installed apps using Intents. Below I demonstrate a simple example (sharing a predefined text) from our Panchanga app. I show the original minimal code used in the app and then give recommended, modern improvements (chooser, file sharing, FileProvider, and package checks).

Create the menu item

The original app added a menu item called "Share". The minimal code used was:

MenuItem share;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    share = menu.add("Share");
    share.setIcon(R.drawable.share);
    share.setOnMenuItemClickListener(this);

    return true;
}

Note: share.png was added to the drawable folder.

Implement the onMenuItemClickListener (original example)

This is the original minimal onMenuItemClick implementation in the article:

public boolean onMenuItemClick(MenuItem menuItem) {

    if (menuItem == share) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
    }

    return true;
}

Here, the system picks all the social apps installed on the device and shows them in the chooser. You can select the required app to send. The text "This is my text to send." is what is sent to other apps.

Below are the images from the original article showing the share chooser and examples:

share1

share2

share3

Share only with a specific app (original note)

If you want to target only a specific app instead of showing a chooser, you can call setPackage on the Intent. Example from the original article:

sendIntent.setPackage("com.whatsapp");

The article linked to the Intent.setPackage docs: http://developer.android.com/reference/android/content/Intent.html#setPackage(java.lang.String)

"com.whatsapp" is the package name of WhatsApp; use the package name of the app you want to target.


Recommended improvements and modern best practices

Keep the original minimal examples (above) for reference, but use these improvements for production apps.

1) Always use a chooser so the user sees a consistent share sheet

Replace startActivity(sendIntent) with:

startActivity(Intent.createChooser(sendIntent, "Share via"));

This forces the chooser UI and avoids launching a default app unexpectedly.

2) If targeting a specific package, check that the package exists first

PackageManager pm = getPackageManager();
if (pm.getLaunchIntentForPackage("com.whatsapp") != null) {
    sendIntent.setPackage("com.whatsapp");
    startActivity(sendIntent);
} else {
    // App not installed — fall back to chooser
    startActivity(Intent.createChooser(sendIntent, "Share via"));
}

Wrap startActivity in try/catch(ActivityNotFoundException) as a final fallback.

3) Sharing files (images, PDFs) — use EXTRA_STREAM and FileProvider on Android N+

When sharing a file (image, PDF, etc.) use a content:// URI and FileProvider for API 24+ to avoid FileUriExposedException.

Example (sharing a single image):

File file = new File(getFilesDir(), "shared_image.jpg");
Uri contentUri = FileProvider.getUriForFile(context, "your.package.name.fileprovider", file);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share image"));

You must declare a FileProvider in your AndroidManifest.xml and add a file_paths.xml resource describing the shared paths. See the official docs for details: https://developer.android.com/reference/androidx/core/content/FileProvider

4) Sharing multiple files

Use ACTIONSENDMULTIPLE with an ArrayList in EXTRA_STREAM:

ArrayList<Uri> uris = new ArrayList<>();
// add multiple content URIs
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share images"));

5) Attach subject or title when appropriate

For email apps, add EXTRASUBJECT and/or EXTRATITLE:

sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Check out Panchanga");
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");

Note: some apps (notably Facebook) ignore prefilled text in shared content due to their platform policy.

6) MIME types and behaviour

Set the right MIME type: text/plain for text, image/* for images, application/pdf for PDFs. A wrong MIME type may hide some target apps from the chooser.

7) Runtime permissions

If the files you want to share are on external storage, ensure you handle runtime permissions (READEXTERNALSTORAGE) on Android 6.0+.

8) Troubleshooting and UX notes

  • If the chooser shows no apps, check the MIME type and ensure there is at least one app that handles the action and MIME type.
  • If you target a specific package and the app is not installed, handle it by notifying the user or falling back to the chooser.

Conclusion

The original minimal example is valid for sharing simple text. For robust production behavior across Android versions, add a chooser, handle URIs with FileProvider, set correct MIME types, and guard setPackage with a PackageManager check. That will give a safer and more consistent user experience.

Happy Coding!

Sudoku Game Development in Android — Features & Google Play Link

Greetings of the Day!!!

When I was learning Android, I thought of developing a game. The easiest was a Sudoku game. And when I was reading an Android book I saw a basic example of the game and thought of using it and building on top of it. So I started it and completed it for a single game. But I did not share it with anybody. When I was cleaning up the things today I saw that game and thought of sharing it.

Overview

I extended the basic example into a small Android Sudoku app with multiple levels, game persistence, and an in-app Settings screen. The app opens with the previous settings and can remember and resume the last-in-progress game.

Features

  • Levels: Easy, Medium and Hard
  • Multiple puzzles per level; when you select a level the app randomly picks a puzzle for you to play
  • Resume: the app remembers the current game state so you can leave mid-way and continue later
  • Settings: options to show hints and to play music; settings are stored using SharedPreferences so they persist across app restarts

Technical notes

  • Level selection: the app presents predefined puzzles grouped by difficulty and randomly selects a puzzle from the chosen level.
  • Persistence: current game state is saved so a paused or interrupted game can be resumed. Settings (hints, music) are implemented with SharedPreferences so they persist when the app is closed and reopened.

(If you want more developer-focused detail — e.g., code snippets showing how game state is serialized or how SharedPreferences are used — I can add minimal, copy-paste-ready examples.)

Screenshots

aboutpng

splash

main

Capture

level

settings

Download

You can download the game from Google Play:

https://play.google.com/store/apps/details?id=com.marutsoft.sudoku

Notes and next steps

  • This post is a short introduction and screenshots from the app. If you want a follow-up developer post, I can add concrete implementation details: puzzle storage format, random selection algorithm, how I save and restore game state, and code showing SharedPreferences usage for settings. Tell me which part you want first and I will publish a technical walk-through.

Tuesday, May 12, 2015

Change TabHost Tab Colors in Android — Set Selected & Unselected Colors

Introduction

In Android you can change the color of TabHost tabs. By default the TabHost appearance is grey. In this example the author changes the unselected tab color to #A45D0A (dark orange / brown tone) and the selected tab color to #A42C0A (dark red).

This article shows how to initialize tabs (each associated with a ListView in the original example), set initial colors, and update colors inside an onTabChanged listener.

Prerequisites

  • A layout that contains a TabHost (for example, with id R.id.TabHost01).
  • A helper method getTabIndicator(Context, String, Drawable) used in the original example to create a tab indicator view — keep your implementation of that helper.

Code example (corrected and formatted)

// Required imports
import android.graphics.Color;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TabHost.OnTabChangeListener;

// ... inside your Activity / Fragment where popupView is available:
final TabHost tabs = (TabHost) popupView.findViewById(R.id.TabHost01);
tabs.setup();

// Optional: show dividers and custom divider drawable
tabs.getTabWidget().setShowDividers(TabWidget.SHOW_DIVIDER_MIDDLE);
tabs.getTabWidget().setDividerDrawable(R.drawable.custom_tab_indicator_divider);

// Create tab 1
TabHost.TabSpec tab1 = tabs.newTabSpec("tab1");
tab1.setContent(R.id.listView01);
tab1.setIndicator(getTabIndicator(tabs.getContext(), "Dialed", getResources().getDrawable(R.color.white)));
tabs.addTab(tab1);

// Create tab 2
TabHost.TabSpec tab2 = tabs.newTabSpec("tab2");
tab2.setContent(R.id.listView02);
tab2.setIndicator(getTabIndicator(tabs.getContext(), "Missed", getResources().getDrawable(R.color.white)));
tabs.addTab(tab2);

// Create tab 3
TabHost.TabSpec tab3 = tabs.newTabSpec("tab3");
tab3.setContent(R.id.listView03);
tab3.setIndicator(getTabIndicator(tabs.getContext(), "Received", getResources().getDrawable(R.color.white)));
tabs.addTab(tab3);

// Set initial colors: first tab selected color, others unselected
for (int i = 0; i < tabs.getTabWidget().getChildCount(); i++) {
    if (i == 0)
        tabs.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#A42C0A")); // selected
    else
        tabs.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#A45D0A")); // unselected
}

// Handle tab changes
tabs.setOnTabChangedListener(new OnTabChangeListener() {
    @Override
    public void onTabChanged(String tabId) {
        // Reset all tabs to unselected color
        for (int i = 0; i < tabs.getTabWidget().getChildCount(); i++) {
            tabs.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#A45D0A")); // unselected
        }

        // Set the currently selected tab color
        tabs.getTabWidget().getChildAt(tabs.getCurrentTab()).setBackgroundColor(Color.parseColor("#A42C0A")); // selected
    }
});

Notes and explanations

  • The original article used #A45D0A for unselected tabs and #A42C0A for the selected tab. These hex values are preserved above.
  • The helper method getTabIndicator(…) used in setIndicator(…) is not included in the original post — keep your implementation or replace with a standard TextView/ImageView as needed.
  • The code corrects several small issues from the original post (case-sensitive method names and inconsistent variable names). For example, Color.parseColor must be used (not parsecolor), and the listener should reference the same TabHost variable (tabs.getCurrentTab()).

Best practices and improvements to consider

  • Use color resources (res/values/colors.xml) instead of hard-coded hex values:
<color name="tab_selected">#A42C0A</color>
<color name="tab_unselected">#A45D0A</color>

Then use ContextCompat.getColor(context, R.color.tabselected) or getResources().getColor(R.color.tabselected, null) on newer APIs.

  • Prefer using a selector drawable for tab backgrounds instead of changing background color in code. A selector makes state handling simpler and moves styling into XML.

  • Consider modern alternatives: TabHost is an older pattern. For new apps, use TabLayout with ViewPager or ViewPager2 (from the Material components / AndroidX) for better integration and styling.

  • Accessibility: ensure tabs have readable text (high contrast) and consider contentDescription when tabs are primarily icon-based.

  • On API 23+ use ContextCompat.getColor(context, … ) or ResourcesCompat to avoid deprecated calls.

Conclusion

Now populate the data for the ListViews associated with each tab. That’s it — Happy Coding..

Saturday, May 9, 2015

SRSM Panchanga — Manmatha Naam Samvastara data added (Android) – Download & Screenshots

Greetings of the day!!!

Summary

First of all, sorry for the delay in updating the Panchanga app with Manmatha naam data. And thanks to all those who reminded me — I received more than 100 emails requesting the Manmatha naam samvastara update. Earlier I used to get the soft copy of the Panchanga from SRSMutt at least two months before Ugadi; this time they did not send it due to technical issues, so I had to convert the data manually.

What changed

  • Manmatha naam samvastara Panchanga data has been added to the SRSM Panchanga Android app.
  • As of now only the English version of the app is updated. The Kannada version is in progress and will be made available soon.

Where to download

You can download the app from Google Play:

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

(Click the link above to open the Play Store on your device.)

Quick install steps

  • Open the Play Store link on your Android device.
  • Tap Install.
  • After installation, open the app and verify the Panchanga data under the Manmatha naam samvastara section.

Screenshots

Below are some of the app screenshots showing the updated data and features.

SRSM Panchanga screenshot 1

SRSM Panchanga screenshot 2

SRSM Panchanga screenshot 3

SRSM Panchanga screenshot 4

SRSM Panchanga screenshot 5

SRSM Panchanga screenshot 6

SRSM Panchanga screenshot 7

SRSM Panchanga screenshot 8

SRSM Panchanga screenshot 9

SRSM Panchanga screenshot 10

SRSM Panchanga screenshot 11

SRSM Panchanga screenshot 12

SRSM Panchanga screenshot 13

SRSM Panchanga screenshot 14

SRSM Panchanga screenshot 15

SRSM Panchanga screenshot 16

Notes & feedback

  • The Kannada version is in progress and will be released when the Kannada data is ready.
  • If you face issues after installing, please reply to the original post's contact email or use the blog's contact form.

Changelog (brief)

  • Added: Manmatha naam samvastara data (English app release).
  • Pending: Kannada language release (work in progress).

Thank you for your patience and for the many reminders and emails — they helped prioritize this update.

--

(Author)

Friday, May 8, 2015

Add a Custom Title Bar to an Android App (Theme-based, step-by-step)

I was developing a quiz app for a customer. And the requirement was to have a custom header / title for the application that’s horizontally center-aligned on the display. This article shows how to set a custom window title using theme styles, a custom layout, and activity code.

Prerequisites

  • Basic Android project knowledge.
  • Android project — example project named "Quiz" in this article.
  • Files we will touch or create:
  • res/values/styles.xml
  • res/values/colors.xml
  • res/values/themes.xml
  • res/layout/header.xml (custom title layout)
  • AndroidManifest.xml
  • MainActivity.java (or the activity where you want the custom title)

1) Create / update styles.xml

Add the style(s) you want to use for your custom title to res/values/styles.xml. (The original article showed the styles as an image — keep that image below as a visual reference.)

styles example

(If styles.xml is missing in your project, create res/values/styles.xml and add the relevant style tags.)

2) Add colors (colors.xml)

Create res/values/colors.xml and add the color resources you will use in the title / theme. The original colors.xml content was provided as an image (kept below):

colors example

3) Add / update themes.xml

Add the theme that references your custom title style or window features in res/values/themes.xml. The article’s example theme content is available as an image here:

theme example

Make sure the style you created is referenced from the final theme applied to your activity or application.

4) Apply the theme in AndroidManifest.xml

Apply the theme to the whole application or to specific activities in AndroidManifest.xml. The manifest snippet from the original article is included below as an image for reference:

manifest snippet

5) Create the custom title layout (header.xml)

Create a layout resource (for example res/layout/header.xml) that contains the controls you want in the title bar. You can include text, images, logos, or other controls. The original article’s example layout (only text in this case) is shown below as an image:

header layout example

(Another preview of the header layout in the original article:)

header layout example 2

6) Add the code in your Activity's onCreate()

In your activity's onCreate() (e.g., MainActivity.java), add the code required to enable and set the custom window title. The exact code used in the original article was provided as an image — kept below:

activity onCreate snippet

The article’s final run screenshot (customized title bar on top) is below:

final result preview

Troubleshooting

If you forget any of the steps above you may see a runtime exception like this in logcat:

Caused by: android.util.AndroidRuntimeException:
You cannot combine custom titles with other title features

To fix this, add the following in your theme (themes.xml) to disable default title features so the custom title can be used:

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

Alternatively, remove the activity-level theme that includes a title bar (for that particular activity) from AndroidManifest.xml. The original article lists this example manifest attribute used in some cases:

android:theme="@android:style/Theme.Black.NoTitleBar"

Notes and recommendations

  • Keep the images above as visual references, but add textual code blocks (as I’ve suggested in the "Troubleshooting" section) for each code example so readers can copy-paste. In the original post many code examples were only images — that should be corrected.
  • For new projects consider using the AppCompat Toolbar (androidx.appcompat.widget.Toolbar) as the recommended approach. The custom window title method is useful for legacy projects or specific use cases.

That’s it. Happy Coding…